Member-only story

What is Immer in Redux Toolkit?

CodeByUmar
3 min readDec 31, 2024

Immer is a JavaScript library that simplifies working with immutable state by allowing developers to write “mutative” code while keeping the state immutable. In the Redux Toolkit (RTK), Immer is integrated by default, especially in its createSlice and createReducer APIs, making it easier to handle state updates.

The Challenge of Immutability in Redux

Redux requires state to be updated immutably, meaning:

  1. You cannot modify the existing state directly.
  2. You must create a new copy of the state with the necessary updates.

Without Immer, this can lead to verbose and error-prone code, especially when dealing with a deeply nested state.

Example Without Immer:

const initialState = {
user: {
name: 'John',
address: {
city: 'New York',
},
},
};

const reducer = (state = initialState, action) => {
switch (action.type) {
case 'UPDATE_CITY':
return {
...state,
user: {
...state.user,
address: {
...state.user.address,
city: action.payload,
},
},
};
default:
return state;
}
};

This approach works but is tedious and prone to errors.

How Immer Simplifies…

--

--

CodeByUmar
CodeByUmar

Written by CodeByUmar

Full Stack Developer sharing insights on JavaScript, React, and web development. Passionate coder and problem solver exploring new tech. 🚀

No responses yet