Provide a context-like API to listen and update values across multiple uses of the custom hook
I needed to create a custom hook that shared one source of truth, or at least I could trust that all instances synced.
For a minor task, I didn't want to store the value on the app context, nor did I want to create a state on a parent for a hook to use.
I did a lookup on the internet, and I wasn't comfortable with the alternatives, where other libraries have trouble exposing the setter as easily as a regular useState
hook would do, and this is when I thought of this approach!
It's based on an Observer design pattern singleton to sync up values between different instances of the same hook while sharing the same key signature.
import useSingletonState from 'use-react-singleton-state';
const useCounter = (defaultValue: number) => {
const [counter, setCounter] = useSingletonState(
'my-custom-hook',
defaultValue
);
};
export default useCounter;
In this GIF, it is evident that both counters are not connected to the same parent, but they are flawlessly synchronized with the same value.
This is the page structure that you can use to make a comparison with the React Dev Tool shown in the GIF.