Member-only story
Global state using only React Hooks with the Context API (No Redux)

How to create a global application state without Redux using React’s latest built-in features: React Hooks and the Context API
It’s been a year already since I moved from Angular to React, long story short: it was one of the best decisions I have ever made in my programming career. It took me about month to learn all React’s component structure and internals. And since React is a library, creating and managing a global state requires a third-party dependencies like Redux.
Now, with the introduction of the Context API in version 16.3 and Hooks in version 16.8, it can be done from within React and without installing any third-party dependency. Bye Redux! 👋 React can do it on its own now 😉
✨ July 2021 Update: Global state using only React Hooks with the Context API (TypeScript Edition)
We just need two things:
- Context API -
createContext()
to create a store that holds the context (the state). - React Hooks -
useReducer()
hooked to a reducer function designed to access the store to manage the state.
1. ⚛️ Creating a reducer
We create a reducer function, this function works with conjunction with React’s own hook: useReducer()
.
Assuming we’re familiar with Redux already, in the code snippet above there’s a reducer function that takes the state and an action as arguments designed for accessing and managing the global state of the application.
2. 🗄️ Creating a store
To create a global state we need a central store. The store is a higher-order component (HOC) which holds the context (the state).