Redux in 2020: Much, much less boilerplate thanks to ‘@reduxjs/toolkit’

Video: Converting an old code challenge (December 2018) from Redux to Reduxjs/Toolkit

One of the things I’ve found is that a lot of people who decide to use some alternative to Redux (React.Context, MobX, etc.) are doing so because they don’t like how much boilerplate Redux consists of.

Me, I never had much of a problem with Redux boilerplate. Every function was testable, it didn’t have side effects, it was a lot of writing, but it was also really easy to read and reason about.

Additionally, a lot of people who really hate Redux do so because they’ve been put onto projects where a whole lot of unnecessary plugins to Redux have been added — Redux forms, Immutable.JS, Reselector, etc., which really don’t add much value at all to the application but make it very hard to reason about and debug.

But if you look at Redux Toolkit, an opinionated collection of tools which basically does “redux-in-a-box”, both of these problems go away. The biggest change, by far, is the paradigm of “slices” — objects that automatically create actions and reducers for you, and in a way that uses immer.js to just… mutate your store.

I know, you’re never supposed to mutate the store — the whole point of Redux is that you don’t mutate the store, you just create a new one. But immer doesn’t really mutate the store, it mutates a draft of the store, which is then compared with the original store and a new store is made from that comparison.

Long story short: there is a TON of boilerplate removed.

I went back over an earlier project (in the video above) written in 2018 as a code challenge (that got me my current job.) It uses the standard Redux that I’m sure we’re all used to — lots of actions, reducers, switch statements, returning new objects, etc. I replaced it with ‘@reduxjs/toolkit’ and ‘react-redux@7.0+’, to use the useSelector and useDispatch hooks. The amount of boilerplate reduced is astounding.

For example, here’s a gist showing a before-and-after comparison for my Photos reducer in that project.

If you want to see the whole thing: here’s the old code in the Master branch and here’s the new hotness in the redux-toolkit branch. I didn’t bother converting the unit tests over, because this is an academic excercise, but gosh dang, look at all the difference switching to modern Redux does.

Edits:

I’d like to thank u/Labradoodles on Reddit for pointing this out:

Some of the code snippets that were referenced in the article can be made more consistent/easier if you use createAsyncThunk instead of writing your own loading/failure etc states. You also get 100% correct types in your reducers as well which can prevent quite a few bugs.

https://redux-toolkit.js.org/api/createAsyncThunk

Thanks!