How to Optimize the Performance of React-Redux Applications?
Last Updated :
24 May, 2024
Optimizing the performance of React-Redux applications involves several strategies to improve loading speed, reduce unnecessary re-renders, and enhance user experience. In this article, we implement some optimization techniques, that can significantly improve the performance of applications.
We will discuss the different approaches to optimize the performance of React-Redux applications:
Steps to Create a React App and Installing Module
Step 1: Create a React application using the following command.
npx create-react-app redux-app
Step 2: After creating your project folder i.e. redux-app, move to it using the following command.
cd redux-app
Step 3: Install required dependencies like redux, and reselect.
npm i react react-dom redux react-redux reselect
Project Structure:
Project Structure
The Updated dependencies in your package.json file is:
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-redux": "^9.1.2",
"redux": "^5.0.1",
"reselect": "^5.1.0"
}
Use useSelector Wisely
The useSelector hook can cause unnecessary re-renders if not used properly. Make sure you are selecting only the necessary part of the state.
Example: Below is an example to optimize the performance of React-Redux applications using Reselect Library.
CSS
/* App.css */
button {
background-color: rgb(228, 233, 224);
border: 1px solid transparent;
cursor: pointer;
padding: 10px 20px;
margin: 10px;
}
button:hover {
background-color: rgb(77, 197, 77);
}
input,
select {
padding: 10px 20px;
margin: 5px;
}
#App{
display: flex;
flex-direction: column;
align-items: center;
}
JavaScript
// App.js
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { addUser } from './store';
import './App.css'
// UserDetails Component
let count = 1;
const UserDetails = () => {
const dispatch = useDispatch();
const handleAddUser = () => {
const newUser = { name: `User ${count++}` };
dispatch(addUser(newUser));
};
return <button onClick={handleAddUser}>Add User</button>;
};
// UserList Component
const UserList = () => {
const users = useSelector((state) => state.users);
return (
<ul>
{users.map((user, index) => (
<li key={index}>{user.name}</li>
))}
</ul>
);
};
// App Component
const App = () => {
return (
<div>
<UserDetails />
<UserList />
</div>
)
};
export default App;
JavaScript
// store.js
import { createStore } from 'redux';
// Action types
const ADD_USER = 'ADD_USER';
// Action creators
export const addUser = (user) => ({
type: ADD_USER,
payload: user,
});
// Initial state
const initialState = {
users: [],
};
// Reducer
const reducer = (state = initialState, action) => {
switch (action.type) {
case ADD_USER:
return {
...state,
users: [...state.users, action.payload],
};
default:
return state;
}
};
// Create store
const store = createStore(reducer);
export default store;
JavaScript
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import store from './store';
import { Provider } from 'react-redux';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
Output :
Use Selector Output
Normalize State
Ensure your Redux state shape is normalized. This reduces the complexity of your state and helps in efficiently updating and accessing it.
Example: Below is an example to optimize the performance of React-Redux applications using Reselect Library.
CSS
/* App.css */
button {
background-color: rgb(228, 233, 224);
border: 1px solid transparent;
cursor: pointer;
padding: 10px 20px;
margin: 10px;
}
button:hover {
background-color: rgb(77, 197, 77);
}
input,
select {
padding: 10px 20px;
margin: 5px;
}
#App{
display: flex;
flex-direction: column;
align-items: center;
}
JavaScript
// store.js
import { createStore } from 'redux';
import { combineReducers } from 'redux';
// Action Types
const ADD_COMMENT = 'ADD_COMMENT';
const UPDATE_COMMENT = 'UPDATE_COMMENT';
const DELETE_COMMENT = 'DELETE_COMMENT';
// Action Creators
export const addComment = (comment) => ({
type: ADD_COMMENT,
payload: comment,
});
export const updateComment = (id, changes) => ({
type: UPDATE_COMMENT,
payload: { id, changes },
});
export const deleteComment = (id) => ({
type: DELETE_COMMENT,
payload: id,
});
// Initial State
const initialCommentsState = [];
// Comments Reducer
const commentsReducer = (state = initialCommentsState, action) => {
switch (action.type) {
case ADD_COMMENT:
return [...state, action.payload];
case UPDATE_COMMENT:
return state.map(comment =>
comment.id === action.payload.id
? { ...comment, ...action.payload.changes }
: comment
);
case DELETE_COMMENT:
return state.filter(comment => comment.id !== action.payload);
default:
return state;
}
};
// Root Reducer
const rootReducer = combineReducers({
comments: commentsReducer,
});
// Create Store
const store = createStore(rootReducer);
export default store;
JavaScript
// App.js
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { addComment, updateComment, deleteComment } from './store';
import './App.css'
const App = () => {
const dispatch = useDispatch();
const comments = useSelector(state => state.comments);
const handleAddComment = () => {
const newComment = {
id: Date.now().toString(),
content: 'New Comment'
};
dispatch(addComment(newComment));
};
const handleUpdateComment = (id) => {
const updatedComment = { content: 'Updated Comment' };
dispatch(updateComment(id, updatedComment));
};
const handleDeleteComment = (id) => {
dispatch(deleteComment(id));
};
return (
<div>
<h1>
<img src='https://media.geeksforgeeks.org/gfg-gg-logo.svg' alt='gfg_logo' />{" "}
Comments
</h1>
<button onClick={handleAddComment}>Add Comment</button>
<ul>
{comments.map((comment) => (
<li key={comment.id}>
{comment.content}
<button onClick={
() => handleUpdateComment(comment.id)}>
Update
</button>
<button onClick={
() => handleDeleteComment(comment.id)}>
Delete
</button>
</li>
))}
</ul>
</div>
);
};
export default App;
JavaScript
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import store from './store';
import { Provider } from 'react-redux';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
Output:
Normalize State Output Split Reducers
Break down your reducers to handle smaller slices of state. This can make state management more efficient and avoid re-rendering.
Example: Below is an example to optimize the performance of React-Redux applications using Reselect Library.
CSS
/* App.css */
button {
background-color: rgb(228, 233, 224);
border: 1px solid transparent;
cursor: pointer;
padding: 10px 20px;
margin: 10px;
}
button:hover {
background-color: rgb(77, 197, 77);
}
input,
select {
padding: 10px 20px;
margin: 5px;
}
#App{
display: flex;
flex-direction: column;
align-items: center;
}
JavaScript
// store.js
import { createStore, combineReducers } from 'redux';
// Action types
const ADD_TASK = 'ADD_TASK';
const ADD_CATEGORY = 'ADD_CATEGORY';
// Action creators
export const addTask = (task) => ({ type: ADD_TASK, payload: task });
export const addCategory = (category) => ({ type: ADD_CATEGORY, payload: category });
// Initial state
const initialTasksState = { tasks: {} };
const initialCategoriesState = { categories: {} };
// Tasks reducer
const tasksReducer = (state = initialTasksState, action) => {
switch (action.type) {
case ADD_TASK:
return {
...state,
tasks: { ...state.tasks, [action.payload.id]: action.payload },
};
default:
return state;
}
};
// Categories reducer
const categoriesReducer = (state = initialCategoriesState, action) => {
switch (action.type) {
case ADD_CATEGORY:
return {
...state,
categories: {
...state.categories,
[action.payload.id]: action.payload
},
};
default:
return state;
}
};
// Root reducer
const rootReducer = combineReducers({
tasksState: tasksReducer,
categoriesState: categoriesReducer,
});
// Create store
const store = createStore(rootReducer);
export default store;
JavaScript
// App.js
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { addTask } from './store';
import './App.css'
// TaskForm Component
const TaskForm = () => {
const dispatch = useDispatch();
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const task = {
id: Math.random().toString(36).substr(2, 9),
name: formData.get('name'),
categoryId: formData.get('category'),
};
dispatch(addTask(task));
e.target.reset();
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="name" placeholder="Task Name" required />
<select name="category" required>
{[1, 2, 3].map((categoryId) => (
<option key={categoryId} value={categoryId}>Category {categoryId}</option>
))}
</select>
<button type="submit">Add Task</button>
</form>
);
};
// TaskList Component
const TaskList = ({ categoryId }) => {
const tasks = useSelector((state) => {
return Object.values(state.tasksState.tasks).filter(task => task.categoryId == categoryId);
});
return (
<div>
<h3>Category {categoryId} Tasks</h3>
<ul>
{tasks.map((task) => (
<li key={task.id}>{task.name}</li>
))}
</ul>
</div>
);
};
// App Component
const App = () => (
<div>
<img src='https://media.geeksforgeeks.org/gfg-gg-logo.svg' alt='gfg_logo' />
<TaskForm />
{[1, 2, 3].map(categoryId => (
<TaskList key={categoryId} categoryId={categoryId} />
))}
</div>
);
export default App;
JavaScript
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import store from './store';
import { Provider } from 'react-redux';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
Output:
Split Reducer Output
Using Reselect Library
The reselect library in React-Redux creates memoized selectors to efficiently compute state data, ensuring components re-render only when relevant state changes.
Example: Below is an example to optimize the performance of React-Redux applications using Reselect Library.
CSS
/* App.css */
button {
background-color: rgb(228, 233, 224);
border: 1px solid transparent;
cursor: pointer;
padding: 10px 20px;
margin: 10px;
}
button:hover {
background-color: rgb(77, 197, 77);
}
input,
select {
padding: 10px 20px;
margin: 5px;
}
#App{
display: flex;
flex-direction: column;
align-items: center;
}
JavaScript
// store.js
import { createStore, combineReducers } from 'redux';
import { createSelector } from 'reselect';
// Action Types
const ADD_USER = 'ADD_USER';
const ADD_ACTIVITY = 'ADD_ACTIVITY';
// Action Creators
export const addUser = (user) => ({ type: ADD_USER, payload: user });
export const addActivity = (activity) => ({ type: ADD_ACTIVITY, payload: activity });
// Reducers
const usersReducer = (state = [], action) => {
switch (action.type) {
case ADD_USER:
return [...state, action.payload];
default:
return state;
}
};
const activitiesReducer = (state = [], action) => {
switch (action.type) {
case ADD_ACTIVITY:
return [...state, action.payload];
default:
return state;
}
};
const rootReducer = combineReducers({
users: usersReducer,
activities: activitiesReducer,
});
// Selectors
const getUsers = (state) => state.users;
const getActivities = (state) => state.activities;
export const getUsersWithActivities = createSelector(
[getUsers, getActivities],
(users, activities) =>
users.map((user) => ({
...user,
activities: activities.filter((activity) => activity.userId === user.id),
}))
);
const store = createStore(rootReducer);
export default store
JavaScript
// App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { addUser, addActivity, getUsersWithActivities } from './store';
import './App.css'
let userCount = 0, activityCount = 0;
const App = () => {
const dispatch = useDispatch();
const usersWithActivities = useSelector(getUsersWithActivities);
const handleAddUser = () => {
const newUser = { id: Date.now(), name: `User ${++userCount}` };
dispatch(addUser(newUser));
};
const handleAddActivity = (userId) => {
const newActivity = { id: Date.now(), userId, description: `Activity ${++activityCount}` };
dispatch(addActivity(newActivity));
};
return (
<div id='App'>
<div style={{ display: 'flex', alignItems: 'center' }}>
<img src='https://media.geeksforgeeks.org/gfg-gg-logo.svg' alt='gfg_logo' /> {" "}
<button onClick={handleAddUser}>Add User</button>
</div>
<ul>
{usersWithActivities.map((user) => (
<li key={user.id}>
{user.name}
<button onClick={() => handleAddActivity(user.id)}>Add Activity</button>
<ul>
{user.activities.map((activity) => (
<li key={activity.id}>{activity.description}</li>
))}
</ul>
</li>
))}
</ul>
</div>
);
};
export default App;
JavaScript
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import store from './store';
import { Provider } from 'react-redux';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
Output:
Reselect Library Output
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
6 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides DOM-specific methods to interact with and manipulate the Document Object Model (DOM), enabling efficient rendering and management of web page elements. ReactDOM is used for: Rendering Components: Displays React components in the DOM.DOM Manipulation: Al
2 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a
4 min read
React FormsIn React, forms are used to take input from users, like text, numbers, or selections. They work just like HTML forms but are often controlled by React state so you can easily track and update the input values.Example:JavaScriptimport React, { useState } from 'react'; function MyForm() { const [name,
4 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. When rendering a list, you need to assign a unique key prop to each element in th
4 min read
Components in React
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects