Member-only story
What is Immer in Redux Toolkit?
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:
- You cannot modify the existing state directly.
- 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.