Modern web applications have become increasingly complex, with a myriad of state to manage. From user preferences, data loading status, and authentication tokens, managing all these without a reliable state management solution can lead to a mess. This is where React Redux steps into the limelight. 😃
React Redux, often simply referred to as Redux, is a predictable state container for JavaScript/TypeScript applications. It works hand-in-hand with React (although not exclusively) to provide an elegant solution to state management in your applications.
To truly grasp the importance of Redux, let's first understand the challenges developers face without it.
React Redux offers solutions to these challenges by providing the following:
Redux operates on three fundamental principles:
At a high level, the Redux flow can be described as follows:
To integrate Redux with a React application, the library "react-redux" is used. It provides two crucial components:
Now that we've gone over the benefits of React Redux lets create a new app implementing React Redux. We will create a simple TODO task manager, first create a new React app using the following command:
npx create-react-app redux-demo
This will create a new React app called redux-demo, next move into the app directory and install React Redux using the following commands:
cd redux-demo
npm install redux react-redux @reduxjs/toolkit
Next we need to set up the Redux store, create a new folder called "redux" inside the "src" directory. Inside "redux" create a new file called "store.js" and populate it with the following:
// src/redux/store.js
import { configureStore } from '@reduxjs/toolkit';
export const store = configureStore({
reducer: {}
});
We will implement the reducer later. Next we will define a Redux Slice for adding tasks, toggling tasks and deleting tasks. Inside the "redux" folder, create new file called "tasksSlice.js" and fill it with the following:
// src/redux/tasksSlice.js
import { createSlice } from '@reduxjs/toolkit';
export const tasksSlice = createSlice({
name: 'tasks',
initialState: [],
reducers: {
addTask: (state, action) => {
state.push({ id: Date.now(), text: action.payload, completed: false });
},
toggleTask: (state, action) => {
const task = state.find(task => task.id === action.payload);
if (task) {
task.completed = !task.completed;
}
},
deleteTask: (state, action) => {
return state.filter(task => task.id !== action.payload);
}
}
});
export const { addTask, toggleTask, deleteTask } = tasksSlice.actions;
export default tasksSlice.reducer;
Now that we have created the reducer we can now add it it our store file like follows:
// src/redux/store.js
import { configureStore } from '@reduxjs/toolkit';
import tasksReducer from './tasksSlice';
export const store = configureStore({
reducer: {
tasks: tasksReducer
}
});
In the above I have imported the tasks reducer and added it to the reducer object.
Next we will create two components, one to add a new task and one to list tasks. Create a new folder called "components" inside the "src" folder, create a new file called "TaskInput.js" inside the components directory and populate it with the following:
// src/components/TaskInput.js
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addTask } from '../redux/tasksSlice';
function TaskInput() {
const [input, setInput] = useState('');
const dispatch = useDispatch();
const handleSubmit = () => {
if (input) {
dispatch(addTask(input));
setInput('');
}
};
return (
<div>
<input value={input} onChange={(e) => setInput(e.target.value)} />
<button onClick={handleSubmit}>Add Task</button>
</div>
);
}
export default TaskInput;
The above component allows us to add tasks, when the button is clicked an event is dispatched and the store is updated with a new task. Finally we need a component to list the TODOs, create a new file called "TaskList.js" insdie the components directory and populate it with the following:
// src/components/TaskList.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { toggleTask, deleteTask } from '../redux/tasksSlice';
function TaskList() {
const tasks = useSelector((state) => state.tasks);
const dispatch = useDispatch();
return (
<ul>
{tasks.map(task => (
<li key={task.id}>
<span
style={{ textDecoration: task.completed ? 'line-through' : 'none' }}
onClick={() => dispatch(toggleTask(task.id))}
>
{task.text}
</span>
<button onClick={() => dispatch(deleteTask(task.id))}>Delete</button>
</li>
))}
</ul>
);
}
export default TaskList;
Done! Finally we need to edit the App.js to reflect all of these changes. Open up "src/App.js" and edit it to the following:
// src/App.js
import React from 'react';
import { Provider } from 'react-redux';
import { store } from './redux/store';
import TaskInput from './components/TaskInput';
import TaskList from './components/TaskList';
function App() {
return (
<Provider store={store}>
<div className="App">
<h1>Task Manager</h1>
<TaskInput />
<TaskList />
</div>
</Provider>
);
}
export default App;
Now all we have to do it start the application via:
npm run start
You should be redirected to the web browser with a simple app showing. You should also be able to add tasks, toggle tasks and delete tasks.
React Redux offers a structured, scalable and maintainable approach to state management in web applications. Through its principles of a single source of truth, read-only state and pure functions, Redux ensures predictability and consistency. Whether you're a novice or a seasoned developer, integrating Redux into your React applications can profoundly enhance their robustness and your development experience.
I hope this guide has taught you something and have fun trying out Redux in your application. Feel free to improve on the above examples UI. Or maybe even add API calls.
As always you can find the sample code on my Github: https://github.com/ethand91/redux-demo
Happy Coding! 😎
Like my work? I post about a variety of topics, if you would like to see more please like and follow me. Also I love coffee.
If you are looking to learn Algorithm Patterns to ace the coding interview I recommend the following course
If you are interested in using a VPN, I recommend ExpressVPN. If you use the below link you get 30 days for free