📌  相关文章
📜  immer.js reducer - Javascript (1)

📅  最后修改于: 2023-12-03 15:31:22.717000             🧑  作者: Mango

immer.js reducer - Javascript

Immer.js is a library for creating immutable state updates in a more efficient and elegant way than traditional approaches. In this article, we will explore how to use Immer.js with reducers in Javascript.

What is a Reducer?

A reducer is a function that takes in the current state of an application and an action object that describes an event in the application. The reducer function then returns a new state based on the combination of the current state and the action object.

Using Immer.js with Reducers

Immer.js provides a produce function that takes in the current state and a function that mutates the state. Within the mutation function, you can make changes to the state as if it were mutable, but under the hood, Immer.js creates a copy of the state with the changes applied.

Here is an example of a reducer using Immer.js:

import produce from 'immer';

const initialState = {
  todos: []
};

function reducer(state = initialState, action) {
  return produce(state, draftState => {
    switch (action.type) {
      case 'ADD_TODO':
        draftState.todos.push(action.payload);
        break;
      case 'REMOVE_TODO':
        draftState.todos.splice(action.payload, 1);
        break;
      default:
        break;
    }
  });
}

In this example, we have a simple todo list application with an initial state of an empty array. The reducer function takes in the state and an action object, and returns a new state using the produce function from Immer.js.

Within the produce function, we use the draftState argument to modify the state as if it were mutable. In the case of adding a todo, we push the new todo onto the draftState.todos array. In the case of removing a todo, we splice the corresponding todo out of the array.

Notice that we are not modifying the original state directly, but instead, we are using the draftState to make changes. Immer.js does the rest by creating a new copy of the state with the changes applied, and returning that as the new state.

Conclusion

Immer.js provides an elegant and efficient way to create immutable state updates in Javascript. By using the produce function with reducers, we can easily update the state without having to write complicated and error-prone code.