Redux Toolkit with Typescript

Redux Toolkit is a really exciting new library from the Redux developers. The project site describes it as “the official, opinionated, batteries-included toolset for efficient Redux development”.

When using React with Redux, I’ve always found writing Redux code a bit cumbersome. Defining action types, actions and reducers always feels like a lot of boilerplate. Plus the Redux core team deliberately leaves Redux unopinionated, so it works for as many use cases as possible. However this leads to a lot of questions to do with structuring state, what is best practice, etc.

Writing reducers is tricky, as they need to be immutable. Thus to simplify writing them, an immutable library can be used. When I started, I thought including a library just to do immutable operations is a bit overkill, I could just use Object.assign() to make copies of the objects and modify the state that way.

However this approach is hard, it’s very easy to make a mistake when trying to modify the state within a nested object, its too easy to accidentally mutate the state. This problem gets harder and harder the more nested your objects are.

Redux Toolkit includes Immer that handles immutable operations for you, such that you can define your reducer logic as mutable operations (similar to how you do it in Vuex).

What it includes

Redux Toolkit includes some popular third party libraries that the Redux developers believe fit with the project’s opinionated vision. These libraries make it much easier to implement Redux logic, and given that they are endorsed by the Redux core team, they will be actively maintained in the future.

These include:

  • immer: For handling immutable objects by defining drafts to apply changes on, this is the recommended way to write reducers (the createReducer function uses immer under the hood).
  • reselect: For writing selector functions, they can make use of memorisation to increase performance.
  • redux-thunk: For writing async actions, which enables moving complex async logic (think auth login flows) out of the component and kept with the store.

I find knowing what’s included in Redux Toolkit gives me an idea of how the authors intended it to be used. Mainly:

  • Use thunks (when it makes sense to)
  • Use Reselect to keep computed data out of the store
  • Use Immer to handle updating immutable state (most of the time Redux Toolkit abstracts this away for you)

Usage with Typescript

The typescript integration is really good, theres no more writing heaps of interfaces and Typescript boilerplate.

Below are some helpful links for setting up Typescript: