createReStateMethods
Use createReStateMethods when a shared state deserves its own module. One call initializes the key and gives you a
complete named API for reading, updating, and resetting it.
import { createReStateMethods } from '@raulpesilva/re-state';
export const { useMuted, useMutedSelect, dispatchMuted, getMuted, resetMuted } = createReStateMethods<'muted', boolean>(
'muted',
false
);import { useMuted } from '../states/muted';
export function MuteButton() {
const [muted, setMuted] = useMuted();
return <button onClick={() => setMuted((previous) => !previous)}>{muted ? 'Unmute' : 'Mute'}</button>;
}The factory runs at module scope, so the key is ready before a component uses one of the generated hooks.
Generated methods
For a state named volume, the returned object contains:
| Method | What it does |
|---|---|
useVolume() | Returns [value, setValue] and subscribes to the key |
useVolumeSelect() | Returns the value and subscribes without exposing a setter |
dispatchVolume(value) | Updates the value from a component, action, utility, or service |
getVolume() | Reads the latest value without subscribing |
resetVolume() | Resets only the volume key |
The generated names use name exactly as provided, except that its first character is capitalized. The name must be
a non-empty string.
Calling the factory again with the same key does not replace that key's current value or original reset baseline.
Set a custom reset value
By default, the generated reset method restores initialValue. Pass { value: ... } as the third argument when the
reset value should be different:
const { dispatchVolume, resetVolume } = createReStateMethods<'volume', number>('volume', 100, { value: 50 });
dispatchVolume(20);
resetVolume(); // volume is now 50The custom value also becomes the baseline used by resetReState. If it is null or
undefined, the generated reset method falls back to initialValue.
API
function createReStateMethods<S extends string = string, V extends any = any>(
name: S,
initialValue?: V | ((previous: V) => V),
valueOfReset?: { value: V }
): ReStateMethods<S, V>;| Parameter | Description |
|---|---|
name | State key and base name used to generate the returned methods |
initialValue | Value or initializer used when the key does not exist |
valueOfReset | Optional object containing a custom reset value |
The returned method names follow this shape:
use<Name>(): [V, (value: V | ((previous: V) => V) | undefined) => void]
use<Name>Select(): V
dispatch<Name>(value: V | ((previous: V) => V) | undefined): void
get<Name>(): V
reset<Name>(): voidFor a one-off shared value, useReState is smaller. Use the
individual factories when you need only part of this API or want custom method names.