Mosh Redux part 5 (cleaner code with reduxjs toolkit)

source code

Here we talk about a powerful library called redux toolkit

Open up a terminal and type:
npm i @reduxjs/toolkit

Redux toolkit provides a bunch of tools to simplify redux code.

One of them is for creating the store. Typically, we extract createStore from redux. Then put your reducers into createStore as a higher order function. We export this store to be used in our index.

If we use createStore way, we have do a lot of stuff manually.

But with redux tookit, we have a new way:

configureStore

We import our reducer(s) from our feature and insert via an object with property reducer:

A pro on using configureStore is that allows us to dispatch asynchronous actions.

Actions with less boilerplate

Typically we create actions by defining constants, then define objects with properties type and payload. The type property uses the defined constants.

However, there is a problem. Every action returns an action like so:

We manually create these by hand.
Redux toolkit has a function called createAction to do this for us.

Hence, in your action creator, we re-factor like so:

Now, in your reducer you can replace the type with our createAction.type:

Notice this:

When we use createAction to create our action object, the parameter we give to createAction is the payload object. Make sure we have properties ‘description’.

make changes in your index.js:

Improving the Reducers

A lot developers don’t like switch statements. Nor do they like returning immutable object patterns.
This is where we can use toolkit. We can create reducer without switch statements. Toolkit uses immer. Automatically translated to immutable update pattern.

Similar to createAction, we use library function createReducer.

When we call this parameter, the first parameter is the initial state

Under the hood, redux toolkit uses immer, so the manipulation of your state gets translated to immutable updated pattern.

Reminder: immer uses function product with initial state. It takes an argument draftState

draftState is actually a proxy. So it will record all changes applied to a copy of the initial state. Thus, preventing the manipulation of the original object.

Thus, our function:

is actually the draftState anonymous function that does the mutating.

By using the functionality from redux toolkit, you can streamline your code nicely:

question.js