Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Beginner

createSlice()

Definition

An RTK function that accepts an initial state, an object full of reducer functions, and a 'slice name', and automatically generates action creators and action types that correspond to the reducers and state.

Explain Like I'm New

The holy grail of modern Redux. It combines Actions and Reducers into one single file. You write a function called `login`, and `createSlice` secretly creates an Action called `auth/login` and links them together perfectly.

Real World Example

Creating a `cartSlice.js` file. You define the initial cart state, and write methods like `addItem` and `removeItem`. You then export the slice to be used by the Store.

Common Use Cases

  • •Defining Redux logic feature-by-feature (Ducks pattern)

Interactive Example

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

const authSlice = createSlice({
  name: 'auth', // This is the prefix for actions
  initialState: { user: null, isLoggedIn: false },
  reducers: {
    // Immer allows us to 'mutate' state safely!
    login: (state, action) => {
      state.user = action.payload;
      state.isLoggedIn = true;
    },
    logout: (state) => {
      state.user = null;
      state.isLoggedIn = false;
    }
  }
});

// createSlice automatically generated these action creators for us!
export const { login, logout } = authSlice.actions;

// Export the reducer to be used in configureStore
export default authSlice.reducer;

Interview Questions

basic

  • What does the `name` property do inside `createSlice`?

intermediate

  • Are you allowed to mutate the state directly inside `createSlice` reducers?

Flash Cards

Question

What does name do?

Click to reveal answer
Answer

It is used as a prefix for the generated action types. If name is `'cart'`, and you have an `addItem` reducer, the generated action type will be `'cart/addItem'`.

Question

Mutate directly?

Click to reveal answer
Answer

Yes! `createSlice` uses the Immer library under the hood. You can write `state.value = 5`, and Immer translates it into a safe, immutable update.