Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Intermediate

What is Immer?

Definition

A tiny package that allows you to work with immutable state in a more convenient way. It is built into Redux Toolkit by default.

Explain Like I'm New

A magic trick for JavaScript. React and Redux strictly forbid 'mutating' data (like `array.push()`). Immer is a library that says: 'Go ahead, use array.push()! I'll intercept it behind the scenes, make a perfect immutable clone, and apply your push to the clone instead of the original.'

Real World Example

Writing Redux reducers that look like dirty, mutation-heavy code, but actually result in perfectly clean, time-travel-safe immutable updates.

Common Use Cases

  • •Simplifying reducer logic
  • •Preventing accidental state mutations

Interactive Example

import { produce } from 'immer';

const baseState = [
  { title: "Learn React", done: true },
  { title: "Learn Redux", done: false }
]

// How Immer works (This is exactly what RTK does inside createSlice)
const nextState = produce(baseState, draftState => {
  // We can push to the array! (Normally forbidden in Redux)
  draftState.push({ title: "Learn Immer", done: false });
  
  // We can reassign properties directly!
  draftState[1].done = true;
});

// baseState is perfectly untouched! Immutable rules are preserved.

Interview Questions

basic

  • Do you need to run `npm install immer` when using Redux Toolkit?

intermediate

  • How does Immer work under the hood?

Flash Cards

Question

Install it?

Click to reveal answer
Answer

No. `createSlice` and `createReducer` from Redux Toolkit already include Immer out of the box.

Question

How it works?

Click to reveal answer
Answer

It uses JavaScript `Proxy` objects. When you modify the 'state' inside a reducer, you aren't actually modifying the real state. You are modifying a Proxy. Immer watches what you do to the proxy, and then generates the final immutable object for you.