1.2.4 • Published 9 months ago

use-react-singleton-state v1.2.4

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

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

1.2.4

9 months ago

1.2.3

9 months ago

1.2.2

9 months ago

1.2.0

9 months ago

1.0.0

9 months ago