use-publish-subscribe
v0.0.6
Published
Hook that can be used to share some state without extracting of the state into parent
Downloads
2
Maintainers
Readme
use-publish-subscribe
Size: 3.39 KB (minified and gzipped). Only React dependency. Size Limit controls the size.
Where can I use it?
The main case is when you need to share some data between 2+ child components, but without rerendering of the parent component.
For example:
import { usePublishSubscribe } from 'use-publish-subscribe'
import { Renderer } from './Renderer.js'
import { Counter } from './Counter.js'
function Parent() {
const [publish, subscribe] = usePublishSubscribe(0)
return (
<>
<Counter onChange={publish}>
<Renderer subscribe={subscribe}>
</>
)
}
// Counter.js
function Counter({ onChange }) {
const counter = useRef(0)
const increase = useCallback(() => {
counter.current += 1;
onChange(counter.current)
}, [counter, publish])
return <button onClick={increase}>Increase</button>
}
// Renderer.js
function Renderer({ subscribe }) {
const [counter, setCounter] = useState(0)
useEffect(() => subscribe(setCounter, true), [setCounter, subscribe])
return <div>Counter: {counter}</div>
}