Register to get access to free programming courses with interactive exercises

More about how slices work React: Redux Toolkit

Let's start diving into Toolkit by looking at slices. Starting from the main point. Whatever we do inside slices, they end up generating the usual reducers and actions, which are then passed to Redux. I.e., slides do not add any new features to Redux itself. They automate routines, reduce the amount of code, and provide more convenient handles for controlling actions and states.

To create a slice, we need at least three components: a name, an initial state, and a set of reducers.

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

// Initial value
const initialState = {
  value: 0,
};

const counterSlice = createSlice({
  name: 'counter',
  initialState,
  // Reducers in slices mutate the state and return nothing to the outside
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1
    },
    // example with data
    incrementByAmount: (state, action) => {
      state.value += action.payload
    },
  },
});

Name

Name is a property in the application state, the data of the current slice are stored in this state In addition, name is used as a prefix in the name of the action. In the picture on the left, it's Navigation. It helps with debugging, as we can see where the action came from.

Redux DevTools

Initial state

The initial state refers to the underlying data structure and some static data, if there is any, such as the value 0 for a counter. But the data that needs to be pumped out via the API does not belong to the initial data. They are filled out later, via actions.

Reducers

Reducers in Toolkit are very similar to the Reducers in Redux itself, but have a few important differences. Each reducer corresponds to a specific action, so there's no switch construction inside, and the reducers themselves are very small. And there is a direct change of state within the Reducers. How is that possible?

Redux, despite conceptually being pure and beautiful, gets quite difficult to work with when the state becomes deeply invested. The prohibition on direct modification generates complex constructs that have to be written to update data hidden quite deep in the application:

{
  ...state,
  firstLevel: {
    ...state.firstLevel,
    secondLevel: {
      ...state.firstLevel.secondLevel,
      thirdLevel: {
        ...state.firstLevel.secondLevel.thirdLevel,
        property1: action.data
      },
    },
  },
}

Many libraries have been written to solve this problem in JavaScript, but they all require you to learn yet another tool, which, although it reduces the amount of code, introduces yet another level of abstraction, with its own problems and complexities. That's what it was like until Immer came along. This library allows you to track direct changes within an object so that you can update the original without mutations, i.e., essentially creating a Redux-style copy.

import produce from 'immer';

const baseState = [
  {
    title: "Learn TypeScript",
    done: true
  },
  {
    title: "Try Immer",
    done: false
  },
];


// draft contains the same data as baseState,
// but they're wrapped in Proxy so changes can be tracked
// These changes are then used to update baseState
const nextState = produce(baseState, (draft) => {
  draft[1].done = true;
  draft.push({title: 'Hexlet teach me'});
});

// Different objects!
nextState !== baseState;

As opposed to directly changing the baseState, Immer does it like the redusers in Redux, in an unchangeable style.

It turns out that every Reducer in Toolkit is the callback from Immer which the draft. is passed to. Now we can mutate the state, but internally, everything works as if we didn't. This approach preserves all the features that Redux provides, including its DevTool, the utility for analyzing what happens in the browser. And this is the best part. We get the perks of both worlds, keeping the entire Redux ecosystem intact.

And finally, exports. The createSlice() function generates a rerenderer and its actions. All of this is recommended by the official documentation to be exported like so: default reducer, name actions:

export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export default counterSlice.reducer;

Don't forget to add each new directory to the store:

export default configureStore({
  reducer: {
    counter: counterReducer,
    lessons: lessonsReducer,
    // and all other reducers
  },
});

Batch

When several slices appear, you need to update the state with several actions at once. If you do it the normal way, then for each action, a component will be redrawn:

// file: components/App.jsx

import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { addUsers } from '../slices/usersSlice.js';
import { addPosts } from '../slices/postsSlice.js';
import Posts from './Posts.jsx';

export default () => {
  const dispatch = useDispatch();

  useEffect(() => {
    const fetchData = async () => {
      // Get data from users and posts
      const { data: posts } = await axios.get('/posts');
      const { data: users } = await axios.get('/users');
      dispatch(addPosts(posts));
      dispatch(addUsers(users));
    });
    fetchData();
  });

  return (<Posts />)
};
// file: components/Posts.jsx

export default () => {
  // Pulling data from the store. state means the whole state
  const users = useSelector((state) => state.usersSlice.users);
  const posts = useSelector((state) => state.postsSlice.posts);

  const renderPost = (post) => {
    const author = users.find((user) => user.id === post.authorId); // error! users not yet added to the store
    const body = `Author: ${author.name}. Text: ${post.body}.`;
    return <div>{body}</div>;
  };

  return (
    {posts.map(renderPost)}
  );
};

The Posts component is rendered whenever the state changes. This happens twice: when we add posts dispatch(addPosts(posts)) and when we add users dispatch(addUsers(users)). In the first case, we have a problem. The author won't be found since users haven't yet been added. To avoid this, we have a special function, batch(), which allows you to combine several state handlers:

// file: components/App.jsx

import React, { useEffect } from 'react';
// importing batch
import { batch } from 'redux';
import { useDispatch } from 'react-redux';
import { addUsers } from '../slices/usersSlice.js';
import { addPosts } from '../slices/postsSlice.js';
import Posts from './Posts.jsx';

export default () => {
  const dispatch = useDispatch();

  useEffect(() => {
    const fetchData = async () => {
      // getting the data of users and posts
      const { data: posts } = await axios.get('/posts');
      const { data: users } = await axios.get('/users');
      // batch takes a function what we can use to dispatch actions
      batch(() => {
        dispatch(addPosts(posts));
        dispatch(addUsers(users));
      });
    };
    fetchData();
  }, []);

  return (<Posts />)
};

Now, when uploading posts and users and adding them to the table, the Posts component is rendered once, when all the data has already been added. Note the internal function fetchData(). According to the documentation, the function passed to useEffect() should not be declared as asynchronous, so we created an internal asynchronous function.


Recommended materials

  1. Patterns for updating data in Immer

Hexlet Experts

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.