
React is an open-source JavaScript library developed by Meta in 2013. React is a very popular tool in building powerful web applications that can handle large traffic and faster loading pages. React has revolutionized the way developers build user interfaces by introducing a component-based architecture that is sufficient for building scalable and dynamic web applications.
React is not limited to building web applications, with the knowled of React Native, you can build apps for different platforms like iOS and Android, supporting cross-platform development.
In this article, we will study about React Redux, their uses, and their core concept. Dan Abramov and Andrew Clark created Redux for the purpose of providing a predictable and centralized way to manage the state management of complex React applications. Its primary purpose is to address the challenges of state management that arise as applications grow in size and complexity.
Redux in React is a state management library for JavaScript applications. It helps you manage the state of your applications in a centralized store, making it easier to debug, test, and scale. Redux is a platform which not limited to React; instead, it can be used with any JavaScript framework or even with plain JavaScript, but it is most commonly used with React through the React-Redux library.
React-Redux follows three basic principles. Given below is the list of three basic principles followed by react.
1. Single Source of Truth: It means that the entire state of your application is stored in a single, centralized JavaScript object within the Redux store. By having a single source, developers eliminate the potential for inconsistencies that can arise when data is duplicated or managed in multiple places.
2. State is Read-Only: In Redux, the state is considered read-only and immutable. This is a fundamental principle of Redux and ensures predictable state management. This means direct modification of the Redux state is not permitted. The only way to change the state is by dispatching an action, which is an object describing what happened.
3. Changes are Made with Pure Functions: To specify how the state changes in response to actions, you write reducers that are pure functions that return a new state. In Redux, state changes are exclusively handled by a pure function called reducers. This core principle of Redux ensures predictability and maintainability of the application’s state.
When your React app becomes large, managing state through props can get messy. For example:
Redux solves these problems by:
• Centralizing the state in a single store.
• Allowing any component to access or update the state directly through actions.
• Making the state changes predictable and easy to track.
Before we dive into coding, let’s understand the main building blocks of Redux.
1. Store: The store holds the entire state of the application. There is only one store per app.
2. Action: An action is an object that describes what you want to do.
For example, if you want to increase a counter, your action might look like this:
const incrementAction = {type: ‘INCREMENT’};
3. Reducer: A reducer is a function that determines how the state changes based on an action.
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;
}
}
Reducers are pure functions – they do not modify the existing state but return a new one.
4. Dispatch: To change the state, you dispatch an action.
store.dispatch({type: ‘INCREMENT’ });
5. Subscribe: You can subscribe to get updates whenever the state changes.
Store.subscribe(() => console.log(store.getState()));
Let’s go step by step through a simple example.
Step 1: Create a New React App: Step 1: Create a New React App
If you don’t have one yet, create a React project using:
Step 1: Create a new React App
If you don’t have one yet, create a React project using:
npx create-react-app redux-demo
cd redux-demo
Step 2: Install Redux and React-Redux
Install both libraries:
npm install redux react-redux
redux -> Core Redux library.
React-redux -> Connects Redux with React components.
Example: Building a simple app
We’ll build a small counter app using Redux to understand the workflow.
Step 3: Create the Redux Setup
Create a folder called redux inside the src/
Inside it, create three files:
• actions.js
• reducer.js
• store.js
actions.js
export const increment = () => {
return {type: ‘INCREMENT’ };
};
export const decrement = () => {
return { type: ‘DECREMENT’ };
};
reducer.js
```javascript
const initialState = { count: 0 };
const 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;
store.js
import {createStore} from ‘redux’;
Import counterReducer from ‘./reducer’;
const store = createStore(counterReducer);
export default store;
Step 4: Connect Redux to React
In index.js, wrap your component with the Redux Provider.
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import App from ‘./App’;
import {Provider} from ‘react-redux’;
import store from ‘./redux/store’;
ReactDOM.render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById(‘root’)
);
Step 5: Using Redux in a Component
Given below is the code for using Redux hooks in App.js
import React from ‘react’;
import { useSelector, useDispatch } from ‘react-redux’;
import { increment, decrement } from ‘./redux/actions’;
function App() {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div style = {{ textAlign: ‘center’ , marginTop: ‘60px’ }}>
<h2>React Redux Counter</h2>
<h3>Count: {count}</h3>
<button onClick={() => dispatch(increment()) }>Increment</button>
<button onClick={() => dispatch(decrement()))}>Decrement</button>
</div>
);
}
1. Centralized State Management: Redux allows you to store your app’s data in a single, predictable store.
2. Easier Debugging: Using Redux DevTools, you can track every state change and action dispatched.
3. Predictable Behavior: In Redux, reducers are pure functions that ensure consistent state transitions.
4. Improved Maintainability: Because of the availability of separate logic, such as reducers and actions in Redux from UI components, the maintainability is improved.
Given below is the list of best practices for using Redux in React for beginners.
1. Keep Reducers Pure: Reducers must never be mutated on existing state or action objects directly. Instead, when updating the state, always return a new state object with the necessary changes.
2. Use Constants for Action Types: You should define constants for action types in order to avoid typing and spelling mistakes.
3. Structure Your files Clearly: The files must be stored in a proper format, like organizing Redux files in folders such as /actions, /reducers, and /store.
4. Use Redux Toolkit: Redux Toolkit is a very special tool that simplifies boilerplate code and setup.
5. Use DevTools: For better debugging and visualization in your code, install the Redux DevTools extension.
Redux is a powerful tool that ensures consistent behavior and makes debugging easier. It easily integrate with react and helps in maintaining a single source of truth. Redux gives a predictable state management solution.
This article describes Redux in React with working code.
To know more about React and other languages, you can visit the Tpoint Tech Website, a platform that provides structured courses for different programming languages and other technologies, along with interview questions, working codes, and an online compiler where you can run and test your code.