Skip to content

About

A component's state as a SyncState (see utils/SyncState.ts): read with state.get('path'), write with state.set('path', value), and the component re-renders whenever a set changes something (the `updateEvent`)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

@atomic-reactor/use-sync-state

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.

Install

npm install --save @atomic-reactor/use-sync-state

react (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.

Usage

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>
  );
}

useSyncState(initialState?, updateEvent?)

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.

No stale closures

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);
}, []);

Compatibility

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+.

License

MIT

About

A component's state as a SyncState (see utils/SyncState.ts): read with state.get('path'), write with state.set('path', value), and the component re-renders whenever a set changes something (the `updateEvent`)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages