Diego Betto's Blog
React logo

June 1, 2022 · 1 min di lettura

React: useContext with useState

How to combine useContext and useState in React to share state and its update function between components, with a live example.

Condividi:XLinkedInFacebookWhatsApp

In the guide to useContext we saw how to share data between components without props drilling. A very common use case is combining useContext with useState: we don’t just share a value, but also the function to update it, so that any child component can read and modify the shared state.

The pattern

The state lives in a Provider component, together with its setter, and gets passed to the Context as a value:

const CounterContext = createContext();

const CounterProvider = ({ children }) => {
  const [count, setCount] = useState(0);

  return <CounterContext.Provider value={{ count, setCount }}>{children}</CounterContext.Provider>;
};

Any component nested inside CounterProvider can then read count and call setCount via useContext, without needing to receive them as props:

const Counter = () => {
  const { count, setCount } = useContext(CounterContext);

  return <button onClick={() => setCount(count + 1)}>You clicked {count} times</button>;
};

Live example

Here’s a complete, interactive example on CodeSandbox:

If your state starts becoming complex, with many different actions, it’s worth considering useReducer instead of useState.

Condividi:XLinkedInFacebookWhatsApp