A tiny React hook that gives a component its own
@atomic-reactor/sync-state
SyncState and re-renders the component when the state changes. Works in
React DOM and React Native, and ships ESM, CommonJS and TypeScript types.
npm install --save @atomic-reactor/use-sync-statereact (16.8+) is a peer dependency. @atomic-reactor/sync-state is
installed with this package, and its SyncState is re-exported, so one
import covers both.
import { useSyncState } from '@atomic-reactor/use-sync-state';
export function Counter() {
const state = useSyncState({ count: 0 });
return (
<button onClick={() => state.set('count', state.get('count') + 1)}>
Clicked {state.get('count')} times
</button>
);
}| Argument | Description |
|---|---|
initialState |
The starting state. Only read on the first render. Defaults to {} |
updateEvent |
The SyncState event that re-renders the component. Defaults to 'change' |
Returns a SyncState: read with state.get('path'), write with
state.set('path', value). With the default 'change' event, the component
re-renders only when a set actually changes a value; a silent
state.set('path', value, true) never re-renders. Pass 'set' to re-render
on every set, changed or not.
The same SyncState is returned on every render, so listeners and effects
registered once can safely read current values from it:
const state = useSyncState({ query: '' });
useEffect(() => {
const onKey = () => console.log(state.get('query'));
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, []);The hook uses only React and ES2019 built-ins and is compiled to ES2019, so it needs no polyfills in any current browser, React Native 0.60+ or Node 12+.
MIT