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?