DEV Community

edem-cyber
edem-cyber

Posted on

Set up Redux-Toolkit in 5 steps

Before you begin, understand that you will understand how to implement and use redux-toolkit by the end of this tutorial. This tutorial is a step by step structured way to understand implementing redux-toolkit.

You can always refer back to this when you need. The key to understanding redux at the core is actually implementing it a lot in projects.

Note: This does not involve the use of asynchronous functions.

Definitions:

Refer to these definitions whenever needed. Make sure you get what they mean. If you don’t, try giving it in an LLM like ChatGPT to explain it to you.

  • Slice: A slice is a concept introduced by Redux Toolkit that helps you organize your Redux store by grouping together the related reducer logic into a single file. It includes reducer functions, action creators, and selectors that work together to manage a specific part of your application state.
  • Reducer: A reducer is a function that takes the current state and an action as arguments, and returns a new state based on the action that was dispatched.
  • Action: An action is an object that represents an intention to change the state. It contains a type field that describes the action and a payload field that contains data relevant to the action.
  • Selector: A selector is a function that takes the current state as an argument and returns a specific piece of data from that state. Selectors can help simplify your code by abstracting away the details of how the state is structured.
  • Middleware: Middleware is a function that sits between the dispatching of an action and the processing of that action by a reducer. It can be used for tasks like logging, error handling, or async operations.
  • Thunks: Thunks are a type of middleware that allows you to write async logic that interacts with the store. They are used to dispatch actions that require async processing, such as fetching data from an API.
  • Store: The store is the single source of truth for your application's state. It holds the current state tree of your application, and allows you to dispatch actions to update that state.
  1. set up store
import { configureStore } from '@reduxjs/toolkit';

export default configureStore({
  reducer: {},
});
Enter fullscreen mode Exit fullscreen mode
  1. include store in app.js
import { Provider } from 'react-redux';
import store from './app/store';


// ...
  <Provider store={store}>
    <App />
  </Provider>
Enter fullscreen mode Exit fullscreen mode
  1. create a slice.
import { createSlice } from '@reduxjs/toolkit';

export const todoSlice = createSlice({
  name: 'todos',
  initialState: [],
  reducers: {
    addTodo: (state, action) => {
      const todo = {
        id: uuid(),
        text: action.payload,
      };

      state.push(todo);
  },
});

// this is for dispatch
export const { addTodo } = todoSlice.actions;

// this is for configureStore
export default todoSlice.reducer;
Enter fullscreen mode Exit fullscreen mode
  1. add slice to store
import { configureStore } from '@reduxjs/toolkit';
import todoReducer from '../features/todo/todoSlice';

export default configureStore({
  reducer: {
    todos: todoReducer,
  },
});
Enter fullscreen mode Exit fullscreen mode
  1. access and retrieve using useSelector and useDispatch useSelector
import React from 'react';
import { useSelector } from 'react-redux';

export default function Todos() {
  const todos = useSelector((state) => state.todos);
  // todos comes from the reducer attribute name
  // in configureStore

  return (
    <div>
      <ul>
        {todos.map((todo) => (
          <li key={todo.id}>
            <span>{todo.text}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

useDispatch

import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addTodo } from '../features/todos/todosSlice';

export default function AddTodo() {
  const [text, setText] = useState('');
  // initial the dispatch here
  const dispatch = useDispatch();

  const addTodoHandler = (event) => {
    event.preventDefault();
    // update the state here using addTodo action
    // action only receive one parameter, which is payload
    dispatch(addTodo(text));
    setText('');
  };

  return (
    <form onSubmit={addTodoHandler}>
      <input
        type='text'
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
      <button>Add todo</button>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

Congratulations!, you are have joined one of the chosen.

Top comments (0)