Can React Hooks useReducer and useContext replace Redux?
Updated: Jul 20, 2020
As soon as React hooks were introduced, the buzz around useReducer and useContext hooks replacing Redux gained traction. However, within the React developer community, there are conflicting opinions regarding the ability of hooks to fully replace Redux. Let us explore this further in this blog.
Before delving into the topic, let us first see What is Redux?. It is a state management platform that separates the application state and maintains the entire state in the form of a single store object. The state can be passed as props from the store object to any React component within the application. This is achieved using the connect API of Redux.
In this blog, let us see two examples. The first example is a class component that uses Redux and the second example is a functional component that uses hooks (useReducer & useContext) to maintain a data store. In both examples let us ignore actions file and side effects like API calls and focus on how the datastore is connected to the React component.
A React component that uses the Redux store will use the connectAPI of Redux, which is a Higher-order component. This adds a significant number of wrapper components in the React Virtual DOM.
The connect API uses two functions mapStateToProps and mapDispatchToProps to map state and actions to the component props respectively.
One of the biggest advantages of Redux is Time Travel Debugging. React dev tools allow developers to debug the state by maintaining a copy of the state on every update.
A Simple React class component which uses Redux
Next, let us explore React Hooks. React hooks are new React API’s which allow using React state and lifecycle methods from within functional components, thereby eliminating the need for messy class components. Hooks also allows the creation of custom hooks which allows reusing of logic in multiple components.
First, let us write a simple reducer and create a context.