The Redux Toolkit package is intended to be the standard way to write Redux logic. It simplifies the store creation and decreases the amount of boilerplate code.
Let's rewrite the application we wrote in one of the earlier posts from scratch to see what will change.
First of all, we need to create a new app. We can use Create React App with TypeScript template and then add Redux Toolkit or we can use a template that already includes everything we need.
Now, if you look in the redux-toolkit-app directory you will see not only App.tsx but also 2 new directories:
app, it contains the store configuration;
features, it contains all the store parts.
For now, let's clear the
features directory, we won't need anything inside of it.
Redux Toolkit introduces a new concept called a
slice. It is an object that contains a reducer function as a field named
reducer, and action creators inside an object called
Basically, a slice is a store part responsible for a single feature. We may think of it as a set of actions, a reducer, and an initial state.
Slices allow us to write less code and keep feature-related code closer thus increasing cohesion.
For our first slice, we're going to use a
createSlice function. Let's start with re-creating typings for our store:
Then, we create an initial state:
And now, we can start creating a slice:
todosSlice object now contains
reducer fields. Let's export everything they have from the module:
To use the state in our components, we need to create a state selector. For that, we need to define a
RootState type. Let's change the
app/store.ts a bit:
Now return to
todosSlice.ts and create a selector:
Using in Components#
The code of our component will be almost the same, except for imports and selector usage. Let's review it:
And the list:
Comparison with “Vanilla Redux”#
We gain some advantages using RTK, such as:
There is much less code than before. We have only 1 file per store part now instead of a bunch of files.
We don't need to “patch” the useSelector hook, it works out of the box.
RTK increases cohesion by making us place the related code closer.
We don't need to type every single action by hand anymore.
There are however disadvantages as well:
RTK is another dependency that will take resources to maintain.