What is a slice?
In redux, a slice is a "slice" of your redux state object.
Actions and reducers per slice
Splitting up reducer logic is an import concept in redux where we compose multiple reducers into one big reducer using combineReducers. For every slice, there is a single corresponding reducer. When building store data inside redux, it is very common to build a set of actions and a reducer that responds to those actions.
What is createSlice?
createSlice is a higher-order function that accepts the slice name (e.g. token, user, todos), a set of reducers, and returns a single reducer along with the action creators for that reducer. The goal of createSlice is to reduce the boilerplate required to add data to redux the canonical way.
The createSlice we know of today from redux-toolkit was inspired by autodux. I helped build the original implementation in redux-toolkit and have been using it for every redux project since. It is a powerful helper function that has gained a ton of popularity in the redux community.
However, it is common for engineers learning redux for the first time to be completely overwhelmed by the terms and phrases used by the redux community. This is exacerbated by the fact that every reducer is now wrapped by createSlice.
So let's build it from the ground up to really understand it!
In order to build our own createSlice we need to build a couple of other helper functions first.
Note: as a learning guide, all of these implementations are simplified versions of the official ones. If you dig into the redux-toolkit source code, you'll see that most of the code are typings and embellishments on top of the code written in this article.
For our example usage we will be recreating redux's example todo list.
createAction is a simple helper function that accepts a string and returns an action creator.
Example usage for createAction
createReducer is a function that accepts an object where the keys are the action type and the values are the reducer.
The redux-toolkit version of createReducer leverages immer to handle state updates. I won't go into the details of how immer works but just know that it is a clever way for the end-developer to appear to mutate their state object while under-the-hood immer actually handles updates to the state in an immutable, redux-friendly manner.
For the purposes of our demonstration, we will not be using immer.
Example usage for createReducer
Okay, now that we have our implementation for createAction and createReducer built, we can move onto building our createSlice.
Example usage for createSlice
This article demonstrates how leveraging a few simple helper functions significantly reduces the amount of boilerplate code required to add state and reducer logic to your redux app. All three of these functions can be used independently of each other. I also hope this article demystifies createSlice, which is now considered the canonical way to use redux.