Skip to content

Implement immer produce function

Daisho Komiyama edited this page Aug 6, 2022 · 1 revision

Immer (German for: always) is a tiny package that allows you to work with immutable state more conveniently.

With Immer, we can leverage the produce function, which takes as first argument the state we want to start from, and as second argument we pass a function, called the recipe, that is passed a draft to which we can apply straightforward mutations.

// from Immer documentation (https://immerjs.github.io/immer/)

const baseState = [
  {
    title: "Learn TypeScript",
    done: true
  },
  {
    title: "Try Immer",
    done: false
  }
]

const nextState = produce(baseState, draft => {
  draft[1].done = true
  draft.push({title: "Tweet about it"})
})

This is a simplified version of produce function.

function produce(state, fn) {
  const copy = JSON.parse(JSON.stringify(state))
  fn(copy)
  return copy
}
Clone this wiki locally