Redux 4.1.0 converts error messages from strings to error code indexes

Providing helpful error messages when things go wrong, makes debugging easier and results in a better developer experience.

But, showing full error messages in the production increases the overhead of sending extra bytes over the wire.

Let’s check out a simple counter example. Here is the CodeSandBox link from the Redux Toolkit tutorial.

The below code defines a string name to identify the slice, an initial state value, and one or more reducer functions to define updating the state.

//counterSlice.js

import { createSlice } from '@reduxjs/toolkit'

export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0,
  },
  reducers: {
    increment: (state) => {
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload
    },
  },
})

export const { increment, decrement, incrementByAmount } = counterSlice.actions

export default counterSlice.reducer

createSlice Api from Redux Toolkit requires initialState to be defined, or else it throws an error. Consider a case where we missed initializing the initialState.

Before

Consider redux-toolkit package has a dependency of redux before 4.1.0 say 4.0.5. In the production environment, the application shows a blank screen, shipping lengthy error messages in the console, which increases the bundle size. This error is better suited for the development environment.

After

With the changes in Redux 4.1.0, all of the error messages are extracted from production builds to save on bundle size. This error message extraction technique is inspired from React’s error code extraction .

In the development environment, the error messages will be shown as normal. But in production, they will reference a specific numeric error code and provide a link to a Redux docs page that has the full error message. This error code extraction saves about 800 bytes out of a production build, overall saving around 30% when minified/bundled.

Without minify

throw new Error(node.process.NODE_ENV === 'production' ? 0 : "This is my error message.");
throw new Error(node.process.NODE_ENV === 'production' ? 1 : "This is a second error message.");

With minify

throw new Error(0);
throw new Error(1);

By updating the dependency redux of redux-toolkit to 4.1.0 for our counter example, we see the below error referencing the error code 12.

The full error message would be displayed in the Redux doc pointing to the error code - 12.

Note:

If there is a new error that is not a part of the existing list, it gets appended to the list with the error code being length-1.

Need help on your Ruby on Rails or React project?

Join Our Newsletter