My Work Notes

01 Jan 2023

How to use createSlice from Redux Toolkit

State management with Redux can be complex and time-consuming. Using slices and the createSlice function from the React Toolkit offers a convenient way to organize and manage state, reducing the amount of boilerplate code and simplifying the development process.

What is a slice?

Here is what Redux documentation says about slices:

A “slice” is a collection of Redux reducer logic and actions for a single feature in your app, typically defined together in a single file. The name comes from splitting up the root Redux state object into multiple “slices” of state.

In other words, a “slice” is a way of organizing and managing a specific piece of the Redux state. It is a pattern that is used to keep the code for managing different parts of the state organized and separated and helps to make the code more maintainable and scalable.

What’s createSlice

The createSlice function is a utility provided by the React Toolkit that makes it easy to create and manage slices of state in a Redux application. It allows developers to define a reducer and a set of action creators in a single function.

What createSlice function accepts

createSlice takes in three main parameters: name, initialState, and reducers.

  • name: a string that specifies the name of the slice. This is used to namespace the actions and selectors, and can be useful for debugging and organization.
  • initialState: the initial state for the slice. This can be any JavaScript value, such as an object, array, or primitive value.
  • reducers: an object that contains “case reducer” functions for updating the state in response to actions. The keys of the object represent the action types, and the values are the reducer functions that handle those actions.

What createSlice function returns

The createSlice returns an object that contains the following properties:

  • name: the name string of the slice
  • reducer: a reducer function for the slice, suitable to pass into Redux’s combineReducers
  • actions: an object containing action creators for dispatching actions to the reducer
  • caseReducers: contain functions passed to the reducers param, can be useful for testing
  • getInitialState: returns an initial state of the slice

Example

Using createSlice is straightforward and requires only a few steps.

Let’s say you need to create a slice of state that contains the user object. To simplify the example, only update this object when user data is fetched from the server.

Create a user slice:

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

const userSlice = createSlice({
  name: 'user', // name of the slice
  initialState: {}, // initial state
  reducers: {
    userFetched: (state, action) => {
      return action.payload;
    },
  }
});

// export the reducer and action creators
export const { userFetched } = userSlice.actions
export default userSlice.reducer

Then add the reducer to the store:

import { configureStore } from '@reduxjs/toolkit';
import articles from './articlesSlice';
import user from './userSlice';

export default configureStore({
  reducer: {
    articles: articles,
    user: user, // adding the user slice
  },
});

Now you can use the userFetched action creator to update the state:

import { useDispatch } from 'react-redux';
import { userFetched } from './userSlice';

const dispatch = useDispatch();

fetch(url, options)
  .then((response) => response.json())
  .then((user) => {
    dispatch(userFetched(user));
  });

In conclusion

Whether you are building a small or large application, the createSlice function from the Redux Toolkit is a valuable and convenient instrument to have in your inventory and can greatly simplify the process of managing the state in your Redux app.