Skip to content

Provide a context-like API to listen and update values across multiple uses of the custom hook

License

Notifications You must be signed in to change notification settings

AndrewLawendy/use-singleton-state

Repository files navigation

useSingletonState

GitHub GitHub package.json version npm GitHub file size in bytes

NPM

Provide a context-like API to listen and update values across multiple uses of the custom hook

Motivation

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!

How it works

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.

Usage

import useSingletonState from 'use-react-singleton-state';

const useCounter = (defaultValue: number) => {
  const [counter, setCounter] = useSingletonState(
    'my-custom-hook',
    defaultValue
  );
};

export default useCounter;

Demo

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.

singleton-state

This is the page structure that you can use to make a comparison with the React Dev Tool shown in the GIF.

structure

Releases

No releases published

Packages

No packages published