Redux provides centralized state management, making it easier to manage and share state across components.
Key takeaways:
Redux simplifies state management by storing all the states in a single, centralized store. This ensures consistent state access across components, avoiding the complexity and redundancy of prop drilling. Local component states can still be managed with React's built-in hooks, while Redux focuses on the global state.
Redux encourages a clear separation between actions, reducers, and the store. Actions handle “what happened,” reducers manage “how the state changes,” and the store maintains the current application state.
With Redux, it's easier to scale your app. As your app grows, Redux’s modular architecture helps developers organize code better by splitting logic into different files (like actions, reducers, and middleware).
Redux is a state management library that helps you predictably manage your application’s state. It works well with React, providing a single source of truth for the application’s state and making it easier to manage and debug. Redux is especially useful in applications where the state is shared across multiple components or where the state needs to be updated frequently and predictably.
Consider the example below, which shows the architecture of a complex React application. In this app, Child 8 and Child 3 must declare the state in their common parent, Child 2, if they want to share it. In this way, Child 7 and Child 6 have to go through unnecessary rendering in order to pass down the props to Child 8.
This is where Redux comes into play. It provides a centralized state that serves as an application’s single source of truth, making it easier to manage and debug state across components.
Follow the steps below to set up the Redux library in your existing React application. We will consider building a simple cash deposit-withdrawal application where users can deposit and withdraw cash.
Note: We assume that you have already created your React Application.
Step 1: Begin with your existing React Application skeleton. The structure of your application should resemble the following:
|-- public|-- index.html|-- src|-- App.css|-- App.js|-- index.js|-- index.css
Step 2: The next step is to install the Redux Toolkit, which includes the core Redux dependencies and other key packages essential for building Redux applications, such as Redux Thunk. Open the terminal and install Redux Toolkit by running the following commands depending on the package manager you are using (like npm
or yarn
):
# For npm package manager:npm install @reduxjs/toolkit# For yarn package manager:yarn add @reduxjs/toolkit
Step 3: Install the Redux library as a dependency.
# For pakage managernpm install redux react-redux# For yarn pakage manageryarn add redux react-redux
Get hands-on practice of integrating Redux in a React app with this project: Integrate Redux in a Front-End Template.
Redux actions are objects that describe what happened in your app. Every action
class has two attributes:
type
: It is a string that represents the type of an action.
payload
: It contains some additional data needed for the action to be performed.
To set up actions, create a folder named myActions
inside the src
directory. Then, create a file named myAction.js
within this folder. This file will create actions for cash deposit and withdrawal:
// Action for depositing cashexport const depositCash = (money) => {return (dispatch) => {dispatch({type:'deposit',payload: money});};};// Action for withdrawal of cashexport const withdrawCash = (money) => {return (dispatch)=>{dispatch({type:'withdrawl',payload: money});};};
Reducers specify how the application’s state changes in response to dispatched actions. To set up reducers, create a folder named myReducers
inside the src
directory. Then, create a file named myReducers.js
within this folder.
For our cash deposit-withdrawal application, we can have the following reducer file where the myReducer
function takes the current state and an action to return a new state based on the action type:
// Takes the initial state and action to be performed as argumentsconst myReducer = (state, action) => {// If the action dispatched by myAction.js file is "deposit", then add the moneyif(action.type === "deposit") {return state + action.payload;}// If the action dispatched by myAction.js file is "withdrawl", then subtract the moneyelse if(action.type === "withdrawl") {return state - action.payload;}// Else keep it in original stateelse {return state;}};export default myReducer;
Learn more about actions and reducers, by trying this project: Build a Resume Builder in React Using Redux.
The Redux store holds the entire state of your application. To set up a store, create a file named myStore.js
inside the src
directory. This file holds the application’s state, dispatches the actions, and notifies the subscribers when the state changes.
For our cash deposit-withdrawal application, the store will look something like this:
import { configureStore } from '@reduxjs/toolkit';// Importing myReducer.js which we created aboveimport myReducer from './myReducer/myReducers';// Define the initial state for the storeconst initialState = 0;const myStore = configureStore({reducer: myReducer,preloadedState: initialState, // Set the initial state here});export default myStore;
In the src/index.js
file, wrap your app inside the Provider
component from react-redux
. This will make the Redux store available across all components to access the relevant state:
import React from 'react';import ReactDOM from 'react-dom/client';import App from './App';import { Provider } from 'react-redux';import myStore from './myStore';const root = ReactDOM.createRoot(document.getElementById('root'));root.render(<Provider store={myStore}><App /></Provider>);
Learn more about building Redux-based React apps with this blog: Building Redux-based React apps.
Let’s look at a working example by combining everything and executing the application.
import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; import { Provider } from 'react-redux'; import myStore from './myStore'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Provider store={myStore}> <App /> </Provider> );
Explore these projects for hands-on practice on Redux and strengthen your understanding of state management through real-world examples and practical applications.
Haven’t found what you were looking for? Contact Us
Free Resources