What is Redux?
Redux is a predictable state container for JavaScript applications. It helps manage the state of your app in a central store, making it easy to pass data across different components
Redux follows a unidirectional data flow:
- State stored in a single, central object.
- Actions are dispatched to modify the state.
- Reducers are pure functions that specifies that how the state changes in response to actions.
Why use redux in react?
- Centralized State: Redux maintains the entire application state in a single store, which makes it easier to manage and debug.
- Predictability: With actions and reducers, the application’s state changes in a predictable manner.
- Debugging: Tools like Redux DevTools allow developers to inspect state changes, replay actions, and even undo/redo changes, making debugging easier.
- Scalability: Redux is great for apps that need to manage global state across many components, reducing the need for prop drilling.
How to Install Redux in Your React Application:
- Install Redux: You need to install redux and react-redux (a library that connects React with Redux).
Run the following command to install both.
npm install redux react-redux - Set Up Redux Store: The store is where the entire state of the application resides. You’ll need to configure it using the createStore() function provided by Redux.
- Connect React with Redux: Use the Provider component from react-redux to pass the Redux store to your React application.
Step-by-Step Guide to Implement Redux
Let’s go through a simple example where we build a counter app using Redux.
- Creating the Redux Store and Reducer:
First, we need to create a reducer that specifies how the state of the counter will change
in response to actions.
Create a file called counterReducer.js:
const initialState = { count: 0, }; function counterReducer(state = initialState, action)
{ switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; case
'DECREMENT': return { count: state.count - 1 }; default: return state; } } export default
counterReducer;
Here, the counterReducer function listens for two actions: INCREMENT and DECREMENT. Based on
the action type, it updates the state.
About the author
Rakesh
Engineering & Product Team at Hornbook Technologies
Hornbook editorial content is written around software delivery, SaaS, cloud engineering, modernization, and practical technology decisions shaped by client work and engineering experience.
View Hornbook on LinkedIn