What is the immer library and how does it work with Redux?

Answer

Immer is a library that lets you write "mutating" code that actually produces immutable updates. It uses JavaScript Proxy to track mutations on a draft state, then produces a new immutable state based on those mutations. Without Immer: case "addTodo": return { ...state, todos: [...state.todos, action.payload] }. With Immer: case "addTodo": state.todos.push(action.payload) — the same result. RTK's createSlice and createReducer use Immer internally. Rules: Either mutate the draft or return a new value — not both. Return undefined implicitly (no return) to commit mutations. Return a new value explicitly to replace state entirely. Limitations: Map and Set have special handling (immer's enableMapSetPlugin). Non-draftable types (Date, RegExp) must be returned, not mutated. current(state) in reducers gives a plain snapshot of the draft for debugging. Immer dramatically reduces the cognitive overhead of writing reducers for nested state structures.