0.0.3 • Published 3 years ago

use-shared v0.0.3

Weekly downloads
6
License
MIT
Repository
-
Last release
3 years ago

useShared npm bundle size

useShared is a shared version of useState that syncs between components. When you setState in one place, other components using the hook for that same data will also re-render (this is basically a React version of an event emitter).

It's a very simple 1 file, 0 dependencies, < 300b state solution. No Provider, no Atoms, and no Selectors like Recoil or Jotai.

Installation

$ yarn add use-shared

Usage

Function signature:

const [state, setState] = useShared(id: string, initialData: any)

setState supports the callback version:

setState((prevState) => prevState + 1)

Example

Share counter state between two different places in your app:

const App = () => {
  return (
    <>
      <Counter />
      <SomethingElse />
      <Counter />
    </>
  )
}

const Counter = () => {
  const [count, setCount] = useShared('counter', 0)

  return <button onClick={() => setCount(count + 1)}>Count is: {count}</button>
}

Normally, each instance of your Counter component would have a separate count state, but useShared will re-render both instances because they are both "subscribed" via the counter id.

SomethingElse, of course, will not re-render when the count changes.

Why?

I've written about using SWR for this use-case, but I needed shared state functionality in a project that wasn't using SWR (yet), so I built a simple version. (I yak-shave a lot on side projects)