React redux toolkit tutorial with code examples
- Get link
- X
- Other Apps
React Redux Toolkit Tutorial with Code Examples
Redux Toolkit (RTK) is the official, recommended way to write Redux logic. It simplifies the process of working with Redux by reducing boilerplate code and offering utilities to manage state in a more efficient and manageable way.
In this tutorial, I'll walk you through how to use Redux Toolkit with React for state management. We'll build a simple Todo List app to demonstrate how Redux Toolkit can help manage state.
1. Setting up the Project
First, make sure you have Node.js
and npm
installed. You can set up a new React project using create-react-app
.
npx create-react-app react-redux-tutorial
cd react-redux-tutorial
Once inside the project, you'll need to install Redux Toolkit and React-Redux.
npm install @reduxjs/toolkit react-redux
2. Creating a Redux Slice
The most important feature of Redux Toolkit is slices. A slice is a collection of Redux reducer logic and actions for a specific feature of your app. In our case, the feature is managing a list of todos.
2.1. Create a slice for Todos
Create a folder called features/todos
and inside that folder, create a file called todoSlice.js
.
src/features/todos/todoSlice.js
import { createSlice } from '@reduxjs/toolkit';
// Define the initial state for todos
const initialState = {
todos: [],
};
// Create a slice of the state
export const todoSlice = createSlice({
name: 'todos', // Name of the slice
initialState,
reducers: {
// Action to add a new todo
addTodo: (state, action) => {
state.todos.push(action.payload);
},
// Action to remove a todo by index
removeTodo: (state, action) => {
state.todos = state.todos.filter((todo, index) => index !== action.payload);
},
},
});
// Export the actions to be used in components
export const { addTodo, removeTodo } = todoSlice.actions;
// Export the reducer to be used in the store
export default todoSlice.reducer;
3. Configuring the Store
Now that we have a slice for managing our todos, the next step is to configure the Redux store.
3.1. Create the store
Create a new file called store.js
inside the src
folder.
src/store.js
import { configureStore } from '@reduxjs/toolkit';
import todoReducer from './features/todos/todoSlice';
// Create the Redux store with the todo slice reducer
export const store = configureStore({
reducer: {
todos: todoReducer,
},
});
4. Connecting Redux with React
To use the Redux store in our React components, we need to wrap our app with the Provider
component from react-redux
and pass the store to it.
4.1. Update index.js
Modify index.js
to provide the store to the entire application.
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import { store } from './store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
5. Creating the Todo List Component
Now, let's create a component to display the todo list and add/remove todos.
5.1. Create the TodoList
Component
src/components/TodoList.js
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { addTodo, removeTodo } from '../features/todos/todoSlice';
const TodoList = () => {
// Local state to handle input value
const [newTodo, setNewTodo] = useState('');
// Get the list of todos from the Redux store
const todos = useSelector((state) => state.todos.todos);
// Get the dispatch function to dispatch actions
const dispatch = useDispatch();
// Handle adding a new todo
const handleAddTodo = () => {
if (newTodo) {
dispatch(addTodo({ text: newTodo }));
setNewTodo(''); // Clear input after adding
}
};
// Handle removing a todo by index
const handleRemoveTodo = (index) => {
dispatch(removeTodo(index));
};
return (
<div>
<h2>Todo List</h2>
<input
type="text"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
placeholder="Add a new todo"
/>
<button onClick={handleAddTodo}>Add Todo</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo.text}
<button onClick={() => handleRemoveTodo(index)}>Delete</button>
</li>
))}
</ul>
</div>
);
};
export default TodoList;
5.2. Update App.js
Now, import and use the TodoList
component inside your main App
component.
src/App.js
import React from 'react';
import TodoList from './components/TodoList';
function App() {
return (
<div className="App">
<h1>React Redux Toolkit Todo App</h1>
<TodoList />
</div>
);
}
export default App;
6. Running the App
Now that the code is in place, you can start the application.
npm start
This will run the app on http://localhost:3000
. You should be able to:
- Add todos to the list.
- Remove todos from the list.
Key Concepts from Redux Toolkit:
- Slices: A slice is a Redux state feature (i.e., managing a feature like todos). It has actions and reducers bundled together.
- Reducers: Functions that define how the state should change based on actions.
- Actions: Functions that describe a change to the state, like
addTodo
orremoveTodo
. configureStore
: A utility function that simplifies store configuration.useSelector
: A hook to access the Redux store state.useDispatch
: A hook that provides a way to dispatch actions to the Redux store.
Advantages of Redux Toolkit:
- Simplified Redux Setup: Redux Toolkit reduces boilerplate and offers simple API calls like
createSlice
to manage the reducers and actions together. - Immutability: Under the hood, Redux Toolkit uses
Immer
to manage immutable updates. - Includes DevTools: It automatically configures Redux DevTools for easy debugging.
- Built-in Middlewares: Redux Toolkit configures popular middlewares like
redux-thunk
andredux-logger
by default.
Conclusion
Redux Toolkit makes it easy to manage global state in a React app. By using the built-in methods like createSlice
and configureStore
, you can streamline your Redux implementation. In this tutorial, we built a simple Todo List app that demonstrates adding, displaying, and removing todos using Redux Toolkit.
By using Redux Toolkit with React, you can create scalable and maintainable applications with less boilerplate.
- Get link
- X
- Other Apps
Comments
Post a Comment