react-common-state

Create a React context which includes a setter, so that children of the context can update the context state.

Usage no npm install needed!

<script type="module">
  import reactCommonState from 'https://cdn.skypack.dev/react-common-state';
</script>

README

react-common-state

Create a React context which includes a setter, so that children of the context can update the context state.

Getting Started

Declare your common state with a default (initial) value. Export the hook, provider, and consumer.

export const [
  useIncrementState,
  IncrementStateProvider,
  IncrementStateConsumer
] = createCommonState(0);

Use the provider as a parent for components which need to observe and mutate a common state. The provider also accepts an optional value property which overrides the default value passed to createCommonState.

render(
  <IncrementStateProvider>
    <IncrementButton />
    <IncrementValue />
  </IncrementStateProvider>
)

Use the hook (or consumer) in a child component. The hook returns a tuple with a value and a value setter, just like the React useState() hook.

export function IncrementButton(): ReactElement {
  const [value, setValue] = useIncrementState();
  const increment = useCallback(() => {
    setValue((prev) => prev + 1);
  }, []);

  return <button onClick={increment}>Increment</button>;
}

Use the hook (or consumer) in another child component which needs to observe the common state.

export function IncrementValue(): ReactElement {
  const [value] = useIncrementState();

  return <span>{value}</span>;
}