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

- Autore / Author: Diego Betto (https://diegobetto.com/about/)
- Pubblicato / Published: 2022-06-01
- URL: https://diegobetto.com/en/react-usecontext-usestate/
- Tag: react, hook, useContext, useState

In the guide to [useContext](https://diegobetto.com/react-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:

```jsx
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:

```jsx
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:

<iframe src="https://codesandbox.io/embed/usecontext-with-usestate-example-c8u1rd?fontsize=14&#038;hidenavigation=1&#038;theme=dark"
style="width:100%; height: 650px; border:0; border-radius: 4px; overflow:hidden;"
title="useContext with useState example"
allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"></iframe>

If your state starts becoming complex, with many different actions, it's worth considering [useReducer](https://diegobetto.com/react-usereducer/) instead of `useState`.
