How to use the default function from immer

Find comprehensive JavaScript immer.default code examples handpicked from public code repositorys.

immer.default is a library for creating immutable states in JavaScript without the need to create copies of the state object.

96
97
98
99
100
101
102
103
104
105
actionKeys.forEach(function (actionKey) {
    var typeKey = namespace + "." + actionKey;
    var reducer = reducers[actionKey];
    reducerMap[typeKey] = (isUseImmer
        ? function (state, payload) {
            return immer_1.default(state, function (draftState) {
                reducer(draftState, payload);
            });
        }
        : reducer);
fork icon0
star icon0
watch icon1

How does immer.default work?

immer.default is a library that provides a simple and efficient way to handle immutable state by allowing you to create a "draft" version of an object that can be safely modified, without affecting the original object. The library uses a technique called "structural sharing" to efficiently track changes made to the draft object and create a new immutable object representing the updated state. The updated state is then made available for use while the original object remains unaltered.

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
import produce from "immer";

const state = {
  counter: 0,
  todos: [{ text: "Learn immer", done: true }],
};

const newState = produce(state, (draftState) => {
  draftState.counter += 1;
  draftState.todos.push({ text: "Use immer", done: false });
});

console.log(newState);

In this example, we first define an initial state object with a counter property and a todos array. We then call produce with this initial state object and a callback function that modifies the state. The produce function returns a new state object that represents the updated state. The original state object remains unchanged.