In Redux Toolkit, a slice is a collection of Redux reducer logic and actions for a single feature of your application. It combines the state, action creators, and reducers for that feature into a single, easy-to-manage unit.
When you define a slice, you provide an object with three main properties:
- name: A string name for the slice that is used as a prefix for the generated action types (e.g., counter/increment).
- initialState: The starting value for that specific piece of the Redux state.
- reducers: An object where the keys are the names of the actions (like increment or decrement) and the values are functions that define how the state should change.
Key Features of a Slice
- Defines a portion of the Redux state (e.g., user, counter, todos).
- Automatically generates action creators and action types based on reducers.
- Simplifies reducer logic by allowing direct state mutation using Immer.
- Keeps related logic (actions + reducers) together for better organization.
Example: Creating a Slice