In React development, data is immutable. To change the state and props, replace the old state with the new state. When changing deeply nested data, the code will be more complex and less readable. Such as:

const { stu } = this.state
this.setState( stu: { ... stu,info: {
      ...stu.info,
      age: stu.info.age + 1}})Copy the code

Immer makes it easy to process immutable data, improving code readability.

introduce

Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way. It is based on the copy-on-write mechanism.

Immer is a library of tools for dealing with immutable data. Immer will make a copy of the data to be changed. During data operations, copy data is directly modified. Finally, the modified copy is treated as the new data.

Refactor the above code with Immer as follows:

import produce from "immer"
const { stu } = this.state
const newStu = produce(stu, draft= > {
  draft.info.age = draft.info.age + 1
})
this.setState({
  stu: newStu
})
Copy the code

Immer also supports Currying(curried, partially evaluated). When produce is called, the function of the data handler is returned when the first argument is a function (a data handler). Such as:

// Bind the data handler function
const mapper = produce((draft, index) = > {
  draft.index = index
})

/ / use
console.dir([{}, {}, {}].map(mapper))
[{index: 0}, {index: 1}, {index: 2}])
Copy the code

To make it easy to use Immer in function components, Immer also provides the React Hook library: use-immer.

import { useImmer } from "use-immer"
const[stu, setStu] = useImmer({... }); setStu(draft= > {
  draft.info.age = draft.info.age + 1
})
Copy the code

Feel good about it, use it in your project

Reference documentation

  • Immer website
  • Immutable data in React – Immer