Skip to content

Latest commit

 

History

History
68 lines (54 loc) · 1.53 KB

createStateContext.md

File metadata and controls

68 lines (54 loc) · 1.53 KB

createStateContext

Factory for react context hooks that will behave just like React's useState except the state will be shared among all components in the provider.

This allows you to have a shared state that any component can update easily.

Usage

An example with a shared text between two input fields.

import { createStateContext } from 'react-use';

const [useSharedText, SharedTextProvider] = createStateContext('');

const ComponentA = () => {
  const [text, setText] = useSharedText();
  return (
    <p>
      Component A:
      <br />
      <input type="text" value={text} onInput={ev => setText(ev.target.value)} />
    </p>
  );
};

const ComponentB = () => {
  const [text, setText] = useSharedText();
  return (
    <p>
      Component B:
      <br />
      <input type="text" value={text} onInput={ev => setText(ev.target.value)} />
    </p>
  );
};

const Demo = () => {
  return (
    <SharedTextProvider>
      <p>Those two fields share the same value.</p>
      <ComponentA />
      <ComponentB />
    </SharedTextProvider>
  );
};

Reference

const [useSharedState, SharedStateProvider] = createStateContext(initialValue);

// In wrapper
const Wrapper = ({ children }) => (
  // You can override the initial value for each Provider
  <SharedStateProvider initialValue={overrideInitialValue}>
    { children }
  </SharedStateProvider>
)

// In a component
const Component = () => {
  const [sharedState, setSharedState] = useSharedState();

  // ...
}