Shared state for React and React Native, without providers.
Shared state without providers
re-state gives shared state the same familiar shape as useState. Give a value a key, and every component that uses
that key stays in sync. There is no provider, reducer, or context wrapper to configure.
Start with a state module
When state belongs to a feature or has its own actions, keep everything in one small module:
import { createReStateMethods } from '@raulpesilva/re-state';
export const { useCounter, useCounterSelect, dispatchCounter, getCounter, resetCounter } = createReStateMethods(
'counter',
0
);import { resetCounter, useCounter } from '../states/counter';
export function Counter() {
const [count, setCount] = useCounter();
return (
<div>
<output>{count}</output>
<button type="button" onClick={() => setCount((previous) => previous + 1)}>
Increment
</button>
<button type="button" onClick={resetCounter}>
Reset
</button>
</div>
);
}The generated hooks keep components subscribed. The dispatcher and getter also work in event handlers, utilities, and other code outside React.
For a one-off value
If you only need a small shared value, use useReState directly:
import { useReState } from '@raulpesilva/re-state';
export function CompactCounter() {
const [count, setCount] = useReState('compact-counter', 0);
return <button onClick={() => setCount((previous) => previous + 1)}>{count}</button>;
}Any mounted component that uses compact-counter reads and updates the same value.
Is re-state a good fit?
re-state works best when one value should be shared across the application or accessed outside React. If you need separate instances owned by different parts of the component tree, React Context may be a better fit. See Context or re-state? for the full comparison.
The package supports React 16.8 and newer, React Native, ESM, CommonJS, and TypeScript.
Start with installation, follow the quick start, or choose an API.