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