When building React applications, we usually manage data using useState. This works well for small applications.
But imagine an application with multiple components that need to access and update the same data.
For example, in a Task Management Application:
- One component adds a task.
- Another component displays the tasks.
- Another component deletes a task.
- Another component updates a task.
Managing the same data across multiple components can become difficult.
What is Redux?
- Redux is a JavaScript library used for managing application state globally.
- In simple words, Redux provides a central place to store application data so that different components can access and update it.
- Instead of passing data from one component to another using props, components can directly access the required data from the Redux store.
What is Redux Toolkit?
Redux Toolkit (RTK) is the official recommended way to write Redux logic.
Earlier, developers had to write more code to configure Redux, create actions, and manage reducers.
Redux Toolkit simplifies this process by providing ready-to-use functions.
Some important benefits:
- Less boilerplate code.
- Easier state management.
- Helps avoid common Redux mistakes.
- Provides useful functions like configureStore() and createSlice().
Installing Redux Toolkit
To use Redux Toolkit in a React project, install these packages:
npm install @reduxjs/toolkit react-redux # NPM
Here:
- @reduxjs/toolkit provides Redux functionality.
- react-redux helps React components communicate with the Redux store.
Important Redux Toolkit Concepts
Before implementing Redux, let's understand some important terms.
1. Store
- The store is the central place where the application's global state is maintained.
- Think of it as a common storage area that different components can access.
2. Slice
A slice represents a particular part of the application state.
For example:
- taskSlice manages tasks.
- userSlice manages user information.
- cartSlice manages shopping cart details.
3. Reducer
A reducer defines how the state should change when an action is dispatched.
For example:
- Add a task.
- Delete a task.
- Update a task.
4. Action
An action describes what operation we want to perform on the state.
For example, addTask tells Redux that a new task needs to be added.
5. Dispatch
dispatch() is used to send an action to the Redux store.
6. useSelector
useSelector() is a React-Redux hook used to read data from the Redux store.
7. useDispatch
useDispatch() is a React-Redux hook used to dispatch actions.
Let's Build a Simple Task Management Application
Now let's understand Redux Toolkit with a practical example.
Our application will support three operations:
- Add a new task.
- Delete an existing task.
- Update an existing task.
Create the Redux Store
Create a file named src/app/store.js. Import the configureStore API from Redux Toolkit. We'll start by creating an empty Redux store, and exporting it:
import {configureStore } from "@reduxjs/toolkit";
import taskReducer from "./taskSlice"
const store = configureStore({
reducer: {}
});
export default store;
configureStore() creates the Redux store and configures the reducers.
Provide the Redux Store to React
Open main.jsx and wrap the App component with the Redux Provider.
createRoot(document.getElementById('root')).render(
<StrictMode>
<Provider store={store}>
<App />
</Provider>
</StrictMode>,
)
Why do we use Provider?
- The Provider makes the Redux store available to all React components inside it.
- Without Provider, components cannot access the Redux store through React-Redux hooks.
Create a Redux State Slice
Create a file named taskSlice.js. In that file, import the taskSlice API from Redux Toolkit.
import {createSlice} from "@reduxjs/toolkit"
const taskSlice = createSlice({
name:"task",
initialState:{
items:[{id:1, title: "task1" ,desc:"welcome to task 1",isCompleted:false}]
},
reducers:{
addTask:(state,action) => {
console.log(action);
state.items.push(action.payload);
},
deleteTask:(state,action) =>{
console.log(action);
state.items = state.items.filter((x) => x.id != action.payload.id)
},
updateTask:(state,action) =>{
state.items = state.items.map((x) =>{
if(action.payload.id === x.id) return action.payload
else return x;
})
}
},
});
export const{addTask,deleteTask,updateTask} = taskSlice.actions;
export default taskSlice.reducer;
createSlice() creates a slice containing:
- Slice name.
- Initial state.
- Reducers.
- Automatically generated action creators.
Add Slice Reducers to the Store
Next, we need to import the reducer function from the taskSlice and add it to our store. By defining a field inside the reducer parameter, we tell the store to use this slice reducer function to handle all updates to that state.
import {configureStore } from "@reduxjs/toolkit";
import taskReducer from "./taskSlice"
const store = configureStore({
reducer: {
task:taskReducer,
},
});
export default store;
Use Redux State and Actions in React Component
Now we can access the Redux state and dispatch actions inside App.jsx.
First, import the required hooks:
import { useSelector, useDispatch } from "react-redux";
import {
addTask,
deleteTask,
updateTask
} from "./taskSlice";
Reading data using useSelector()
const items = useSelector((state) => state.task.items);
This reads the task list from the Redux store.
Dispatching actions using useDispatch()
const dispatch = useDispatch();
We can now dispatch actions whenever we want to add, delete, or update tasks.
For example:
dispatch(addTask({
id: Date.now(),
title: "Learn React",
desc: "Practice Redux Toolkit",
isCompleted: false
}));
This sends the new task to the Redux store.
Similarly, we can delete and update tasks:
dispatch(deleteTask({ id: 1 }));
dispatch(updateTask({
id: 1,
title: "Learn Redux",
desc: "Redux practice completed",
isCompleted: true
}));
How Does Redux Work?
Let's understand the complete flow.
- The user performs an action, such as clicking the Add Task button.
- The component calls dispatch(addTask(...)).
- The action reaches the Redux store.
- The corresponding reducer executes.
- The Redux state gets updated.
- Components using useSelector() receive the updated state and re-render when their selected data changes. used tailwind css
Top comments (0)