re-state
API Reference

createReState

createReState binds a key and initial value once, then returns a named hook with the familiar [value, setValue] tuple.

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

export const useCounter = createReState<number>('counter', 0);
import { useCounter } from '../states/counter';

export function Counter() {
  const [count, setCount] = useCounter();
  return <button onClick={() => setCount((previous) => previous + 1)}>Count: {count}</button>;
}

The factory initializes the key when it runs. Calling another factory with the same key later does not replace the current value or the original reset baseline.

The returned function is a React hook, so call it only from a component or another custom hook.

API

function createReState<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 when the key does not exist

Without an initial value, a new key starts as undefined at runtime.

Use useReState when the key belongs at the hook call site. Use createReStateMethods to generate all helpers for the key together.

On this page