re-state
API Reference

useReState

Use useReState for a small value that several components should share. Components using the same key subscribe to the same state, and no provider is required.

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

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

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

Another component can call useReState('count', 0) to read or update that same count.

What to know

  • initialValue is used only when the key does not exist. Later calls with the same key do not replace it.
  • The setter accepts a new value or an updater function that receives the current value.
  • Updates replace objects and arrays. Return a new value when changing structured state.
  • Without an initial value, a new key starts as undefined at runtime.
  • Like every hook, useReState must be called from a React component or another custom hook.

API

function useReState<S>(
  key: string,
  initialValue?: S | ((previous: S) => S)
): [S, (value: S | ((previous: S) => S) | undefined) => void];
ParameterDescription
keyName that identifies the shared value
initialValueValue or initializer used only when the key is new

Use createReState to bind the key once and create a named hook. Use createReStateMethods when the state also needs actions, a getter, or reset behavior.

On this page