DEV Community

Cover image for What is Redux Toolkit: When and How to use it Effectively?
Hesbon limo
Hesbon limo

Posted on

1 1 1 1 1

What is Redux Toolkit: When and How to use it Effectively?

What is redux

Redux is a predictable state management tool for JavaScript apps. A state is something that keeps the app running for example when you are asked to select gender in a website, the state is either male or female.

Imagine that you are a customer of four banks and in each of those banks you have two accounts. Those will make eight accounts in total. Without Redux, when you want to ask balance or deposit you will have to visit each of the four banks. But with Redux all of these will be stored in one central location called a store.

Why redux

Redux make state management easier. Managing states of small applications is not hard but once an application has a lot of components with different states it becomes harder to manage. Components are independent and reusable pieces of code.

Let's return to the example of banks above. Assuming you have twenty accounts with different banks and some of the banks are in other countries managing the accounts without redux would be nearly impossible.

Advantages of using redux

1. Centralized state management

One of the advantage of using Redux is the ability to manage state in a centralized manner. In React application state is managed in components. However, when an application has so many components it becomes difficult to track the components.

2. Predictable state changes

Redux enforces strict rules on how state is changed. It returns a new state insted of mutating the existing one therefore making it straight forward to predict the change of a state.

3. Simplifies data flow

In a React application data flow may become complex especially when components have to share state. In React data is passed from parent to child using props. Redux simplifies this by allowing any component to access a global state from a central store.

4.Makes debugging easy

Redux offers powerful tools such as Redux DevTools which can be intergrated with the browser. These allows the developer to see states in real time and easily identify errors in the code.

5. Improved code maintainability and readability

Redux separates states with the main UI logic making it easy to maintain and read code. Actions and reducer are also kept distinct making it easy to read code file structure.

Components of redux

1. Redux store

Its the central bucket which stores all the states of an application. It should be maintained as a single source of the application.

2. Actions

States in redux are read only. Therefore, when you want to update or delete something in the store you need to express your intentions by emmitting or dispatching an action.

3. Reducer

Reducer takes in two things, the current state and the action. They the update it to one entity the new state.

4. Dispatcher

The dispatcher is a function used to send actions e.g add Todo to the redux store which is then processed by the reducer and updated accordingly.

Here is a diagram showing the redux components in detail give_your_react_apps_an_edge_mastering_redux_toolkit_0_9c97663b53

Example Project - To Do List Application

Now that you know the basics of Redux, it's time to apply this knowledge in creating a real world app. We will build a simple To Do application where you can add and delete tasks.

Step 1: Prequisites

To build this app you will need a code editor eg sublime text or VS code. For this tutorial I will use Visual Studio Code
.

Step 2: Setting up the Project

Create a new react app by running the following command in the terminal.Make sure you replace "your-project-name" with the name of your project.

npm create vite@latest your-project-name -- --template react
cd your-project-name
npm install
Enter fullscreen mode Exit fullscreen mode

The above command will create a new react app and install the necessary dependancies.

Step 3: Getting Started with Redux

Redux requires some dependancies for it to function well, namely:

  • Redux: The main library that enables the Redux architecture

  • React redux: Enables connection between the React components and the Redux store

  • Redux DEvTools Extension: Connects your Redux application to redux Devtools

  • redux Toolkit: It makes it easier to create Redux store and intergrate middleware like Redux-thunk

Install them using npm as shown below:

npm install\
redux
react-redux\
@reduxjs/toolkit\
redux-devtools-extension
Enter fullscreen mode Exit fullscreen mode

Step 4: How to create the redux store

Now that we have installed everyting and our setup is ready, navigate to the src folder and create a file and name it store.js:

import { configureStore } from '@reduxjs/toolkit';


export const store= configureStore({
    reducer: [],
})
Enter fullscreen mode Exit fullscreen mode

The function of the configireStore we have imported in the first line will help us create the store. We will then create the store by declaring a function named store.

Next, we create an empty reducer where all our state will be handled. Finally in line 4 we export the store so that we can use it in the application.

Step 5: Setting up the reducers and actions in the file structure

Now let's create the reducer in our application. for these code I will combine the reducer and the actions. An action is simply what happens in the application e.g deleting task.

Inside the src directory create a new folder called features, and inside that folder create a file called todoSlice.js.

// src/features/todoSlice.js
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
  todos: [],
};

const todoSlice = createSlice({
  name: 'todos',
  initialState,
  reducers: {
    addTodo: (state, action) => {
      // Ensure you are adding the new todo with an id and text
      const newTodo = {
        id: Date.now(),  // Generate a unique id
        text: action.payload,
      };
      state.todos.push(newTodo);  // Add the new todo to the state
    },
    removeTodo: (state, action) => {
      state.todos = state.todos.filter((todo) => todo.id !== action.payload);
    },
  },
});

export const { addTodo, removeTodo } = todoSlice.actions;
export default todoSlice.reducer;

Enter fullscreen mode Exit fullscreen mode

In line three, we are defining an initial state. In our case an empty array of todos. Then we use the createSlice which is an helper function from the reduxToolkit used to create a slice which is a single piece in the redux.

The slice has the following components:

  • Initial state. This is the default state.
  • Reducer. This is a function that handles how a state changes in response to an action e.g addTodo
  • Action. It is inside the reducer and handles what actually changes e.g remove or add todo

We then export the actions so that we can use them in our components. After that we export the Reducer so that it can be used in the Redux store.

Step 6 : Connecting the store to the main application

The Provider from the react-redux library is all we need to connect the redux store to the ToDo application.

First we import the provider from the react react redux. Then we wrap our app component with ths provider function and pass the store as a prop in the main.jsx or index.js.

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <provider store={store}><App /></provider>
  </StrictMode>,
)
Enter fullscreen mode Exit fullscreen mode

Step 7: Getting started with dispatch actions

Now that we have set up the reducer and the actions we will move on and create components that dispatch the actions.

Let's create a new folder named "components" inside the src directory. In this folder, we will create two files AddTodo.js and todo.js.

The AddTodo.js component will be responsible for adding tasks. Before we proceed lets import the following into the file:

  • React library for creating react components and useState a React hook that enables you to add state to a functional component
  • useDispatch: A react-redux hook that provides the dispatch functin which is used to send actions to redux store, triggering state updates.
  • addTodo: Imports addTodo action from todoSlice which is used to add a new todo item to the Redux store
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addTodo } from '../features/todoSlice';
import './AddTodo.css'; // Import the CSS file
Enter fullscreen mode Exit fullscreen mode

Now, let's proceed to write code for addTodo.js:

function AddTodo() {
  const [input, setInput] = useState("");
  const dispatch = useDispatch();

  const addTodoHandler = (e) => {
    e.preventDefault();

    if (input.trim()) {
      dispatch(addTodo(input));
      setInput("");
    }
  };

  return (
    <form onSubmit={addTodoHandler} className="add-todo-form">
      <input
        type="text"
        className="add-todo-input"
        placeholder="Enter a Todo..."
        value={input}
        onChange={(e) => setInput(e.target.value)}
      />
      <button type="submit" className="add-todo-button">
        Add Todo
      </button>
    </form>
  );
}

export default AddTodo;
Enter fullscreen mode Exit fullscreen mode

In the code above, we created a component consisting of a button and the input field. When a user clicks "Add Todo" button , the AddTodo function is executed. The function uses the input.trim() to remove leading and trailing white spaces from the input and then dispatches the addTodo action with the new task as the payload.

Now, let's move on to the todo.js responsible for rendering the list of tasks and also deleting tasks.

Let's import the following to achieve this:

  • React: for creating react components.
  • useSelector: for retreiving specific pieces of state.
  • useDispatch: for dispatching actions to redux store.
  • removeTodo: for deleting an item.
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { removeTodo } from '../features/todoSlice'; // Adjust the import path based on your project structure
import './todo.css'; // Import the CSS file
Enter fullscreen mode Exit fullscreen mode

Now, let's write the code for todo.js.

function Todos() {
  const todos = useSelector((state) => state.todos.todos);
  const dispatch = useDispatch();

  return (
    <div className="todos-container">
      <h1 className="todos-header">Todos</h1>
      {todos.length > 0 ? (
        todos.map((todo) => (
          <div key={todo.id} className="todo-item">
            <div className="todo-text">{todo.text}</div>
            <button
              onClick={() => dispatch(removeTodo(todo.id))}
              className="todo-delete-button"
            >
              Delete
            </button>
          </div>
        ))
      ) : (
        <div className="no-todos">No todos available.</div>
      )}
    </div>
  );
}

export default Todos;
Enter fullscreen mode Exit fullscreen mode

The code above checks If todos.length > 0 (i.e., there are to-do items), the component maps through the todos array and renders each item.
If todos.length === 0, a message (No todos available.) is displayed.

  • onClick: When the button is clicked, it dispatches the removeTodo action with the todo.id as the payload. This action will remove the specific todo from the Redux store.

Finally, import the components into your App.jsx file and render them.

import React from 'react';
import AddTodo from './components/AddTodo';
import Todos from './components/todo';


function App() {
  return (
    <div className="container mx-auto p-6">
      <h1 className="text-4xl font-bold text-center mb-6">Todo App</h1>


        <AddTodo />
        <Todos />

    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Step 8: Getting Started with Redux Devtools

To get started, download the Redux DevToolsRedux DevTools Extension Extension for your browser.

After the istallation, your browser DevTools will add a new tab specifically for Redux.
Screenshot from 2025-01-08 20-25-53

You will then click on the "State" tab within the Redux DevTools to show you the entire state of your Redux store and any actions that have been dispatched and their payloads.

In the Redux DevTools, click "state". This will show you the entire state of your Redux store and the dispatched actions and their payload.

Final Step

After implementing everything as shown in the tutorial the final product should look like the one below.

Conclusion

Redux is a very powerful state management tool used by a lot of developers all over the world. In this article I have discussed in detail what is Redux, it's advantages and finally a demo project on how to use the Redux tool practically. You can search on YouTube more tutorials about Redux and I am confident that you will grasp the content.

End ...

Happy coding.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more