re-state
Getting Started

Quick start

useReState looks like useState, with one important difference: components that use the same key share the same value.

Create a shared counter

Both components below use the count key, so an update from one is immediately visible in the other:

import { useReState } from '@raulpesilva/re-state';

export function IncrementButton() {
  const [, setCount] = useReState('count', 0);

  return (
    <button type="button" onClick={() => setCount((previous) => previous + 1)}>
      Add 1
    </button>
  );
}

export function CountOutput() {
  const [count] = useReState('count', 0);
  return <output>Current count: {count}</output>;
}

There is no provider to mount. The setter accepts a new value or an updater function, just like the setter returned by useState.

The first initialization wins

The first use of count stores its initial value. Later calls with the same key join that state; they do not replace the current value or its reset baseline.

Keep the initial value consistent wherever you use the same key. For larger features, define the key once in a state module instead of repeating it in components.

Update objects and arrays

Updates replace the current value. When state is an object or array, return a new value instead of mutating the existing one:

import { useReState } from '@raulpesilva/re-state';

type Profile = {
  name: string;
  email: string;
};

const initialProfile: Profile = { name: '', email: '' };

export function NameInput() {
  const [profile, setProfile] = useReState<Profile>('profile', initialProfile);

  return (
    <input
      value={profile.name}
      onChange={(event) => setProfile((previous) => ({ ...previous, name: event.target.value }))}
      placeholder="Name"
    />
  );
}

Use a different key for every independent value. If several components share the same kind of state but should not share the same instance, give each instance its own key.

Next, learn how to build a state module with named hooks and actions.

On this page