re-state
Getting Started

Choose an API

You do not need to learn the whole library before using it. Start with the smallest API that fits your state, then move to a state module when the feature grows.

If you need to...Start with
Share one small value between componentsuseReState
Give a state named hooks, actions, and a resetcreateReStateMethods
Create only one kind of helper for a keyAn individual factory from the API reference
Derive a value from one or more state keysuseReStateSelector

Share a small value

useReState is the quickest way to get started. It returns the same [value, setValue] tuple as useState, but components using the same key share the value:

const [count, setCount] = useReState('count', 0);

Use this for a one-off value shared by a few components. The quick start walks through a complete example.

Give the state a home

When a state has domain logic, is used throughout a feature, or needs to be read outside React, create a module with createReStateMethods:

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

export const { useCounter, useCounterSelect, dispatchCounter, getCounter, resetCounter } = createReStateMethods(
  'counter',
  0
);

export const increment = (): void => {
  dispatchCounter((previous) => previous + 1);
};

The module owns the key and initial value. Components import named hooks and actions instead of repeating those details. See Build a state module for the full pattern.

Derive data from several keys

useReStateSelector receives the complete keyed state object. Use it when a component needs a derived value rather than one key as-is:

const finishedCount = useReStateSelector<AppState, number>(
  (state) => state.todos.filter((todo) => todo.finished).length
);

The keys used by a selector must already be initialized. For a single key without derived data, a generated use<Name>Select hook is simpler.

Keep these rules in mind

  • A key identifies one value in the current JavaScript runtime.
  • The first initialization of a key establishes its value and reset baseline.
  • Updates replace the current value. Create a new object or array when changing structured state.
  • createReState and createReStateMethods initialize a key when their factory runs. Read-only factories do not.
  • Use different keys when you need independent values.

If the scope and lifetime of the state matter more than access outside React, read Context or re-state? before choosing.

On this page