How to make global state management super simple in React

Sean Marcus
2 min readJan 6, 2021

--

Photo by Shahadat Rahman on Unsplash

The useContext hook is the easiest way to manage global state in your React app. A global context paired with the useState hook allows you to manage and share state between components in such a cool and clean way. I love using this design pattern! There’s no need to worry about prop drilling or the complex boilerplate of that comes with using redux.

There are a few simple steps when setting up a global context for your React app. First, we need to simply create a context for our wrapper component to use.

export const Context = React.createContext({})

Notice that we pass it an empty object as the initial value. With this context, we’ll pass in all our state values that need to be managed by child components. Next, we’ll wrap all child components with a <Context.Provider> component that will contain all those context values.

Now that we have wrapped our Child component with a context provider, all we have to do is utilize the useContext hook inside of our child component to access all the values we included.

Magic! Just like that we have global state that’s super easy to handle. Any child component that is wrapped with the context can access anything passed inside of the context provider’s value prop. Woohoo!

--

--

Sean Marcus
Sean Marcus

No responses yet