Explain the concept of Redux in React.
Last Updated :
05 Aug, 2024
Redux is a state management library commonly used with React, although it can also be used with other JavaScript frameworks. It helps manage the state of your application. It was inspired by Flux, another state management architecture developed by Facebook for building client-side web applications. In this tutorial, we'll learn the concept of Redux in React.
Prerequisites:
How does redux work?
- Redux operates by maintaining a centralized state tree, offering a method to manage the application state and address state changes.
- Actions are dispatched to the store, initiating reducers to define how the state should change.
- Reducers, being pure functions, take the previous state and an action as input and produce the new state as output.
- Components can subscribe to the store to access and update the state, ensuring a predictable uni-directional data flow throughout the application.
Steps to Create React Application And Installing Redux:
Step 1: Create a React Vite application and Navigate to the project directory the following command:
npm init vite@latest my-react-redux-project --template react
cd my-react-redux-project
Step 2: Install Redux and React-Redux packages
npm install redux react-redux
Project Structure:
Folder StructureThe updated dependencies in package.json file will look like.
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^9.1.0",
"redux": "^5.0.1"
}
Step 3: Create a new file named store.js in the src directory of your project.
Step 4: Create one or more reducer files inside the src Folder.
Step 5: Create a file named index.js inside the src/reducers directory to Combine reducers.
Step 6: Connect Redux to React.
- Open src/main.js (or src/main.jsx) file.
- Import '<Provider>' from react-redux and your Redux store.
- Wrap your root component with '<Provider>' and pass the Redux store as a prop.
Step 7: Now, Create your React components as usual and use the connect function from react-redux to connect your components to the Redux store.
JavaScript
// src/store.js
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer);
export default store;
JavaScript
// src/reducers/counterReducer.js
const initialState = {
count: 0
};
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
};
export default counterReducer;
JavaScript
// src/reducers/index.js
import { combineReducers } from 'redux';
import counterReducer from './counterReducer';
const rootReducer = combineReducers({
counter: counterReducer
});
export default rootReducer;
JavaScript
// src/components/Counter.jsx
import React from 'react';
import { connect } from 'react-redux';
const Counter = ({ count, increment, decrement }) => {
return (
<div>
<h1 style={{ color: 'green' }}>
GFG Counter App using Redux</h1>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
const mapStateToProps = (state) => ({
count: state.counter.count
});
const mapDispatchToProps = (dispatch) => ({
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' })
});
export default connect(mapStateToProps,
mapDispatchToProps)(Counter);
Start Your Application using the following command:
npm run dev
Output:
Advantages of Redux:
- Centralized State Management: Redux maintains a single, global state tree for effective management of application state.
- Predictable State Changes: Redux follows a clear and predictable pattern where actions trigger reducers to update the state, simplifying debugging and understanding of state changes.
- Unidirectional Data Flow: Redux enforces a unidirectional data flow, making it easy for components to subscribe to the state and ensuring consistency in application behavior.
- Scalability: Well-suited for larger applications, Redux provides a structured approach that scales efficiently as the complexity of the application grows.
Similar Reads
What are the 3 core concepts of React Redux ? Redux is a widely-used state management library that helps in managing the state in our projects. However, it comes with its own terminologies and jargon that can be confusing for beginners. Essentially, Redux comprises of three core concepts: actions, reducers, and store. In this article, we will c
4 min read
Explain Selectors in React Redux Selectors in React Redux serve as efficient filters for accessing specific data from the Redux store. They encapsulate logic for data retrieval, optimizing performance, and promoting code reusability. By using memoization, selectors cache results to prevent unnecessary re-renders, thus enhancing ove
2 min read
What is the use of React Context in React-Redux? React Context is a feature that React provides us to manage states required in multiple components. Redux is also a state management library and solves the same problem that React Context does but in a different way. In this article, we will see in detail what is react context, why and how to use it
5 min read
Explain Actionâs in Redux In this article, we are going to learn about Action in Redux. Actions are plain JavaScript object that contains information. Action is one of the building blocks of Redux. Redux is a state managing library used in JavaScript apps. It is used to manage the data and the state of the application. Uses
5 min read
Explain the Benefits of State Normalization in Redux Redux is a predictable state container for JavaScript apps and offers a powerful solution for managing application states in complex web applications. One strategy that Redux uses is state normalization in which we can restructure state data to improve performance, maintainability, and scalability.
5 min read