10

I have seen some React applications utilize useImmer as a hook instead of useState. I am not understanding what useImmer offers that useState does not.

What is an advantage of using useImmer over using the official useState?

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
randombits
  • 47,058
  • 76
  • 251
  • 433
  • Try this, I think it explains the advantages very well: https://blog.logrocket.com/immutability-in-react-with-immer/ (But be aware it can be an overkill depending on the usage. What I mean is that useState does the trick for most of the situations. – Luis Gouveia Jun 02 '20 at 15:04

1 Answers1

30

In the nutshell, immer facilitates the way you mutate nested/complex data structures. Have a look at these 2 ways:

consider below object:

const [product, updateProduct] = useState({
    name: "Product 1",
    SKU: "SKU-001",
    availability: 30,
    stock: [
      {
        id: 1, 
        store: "Store 1",
        quantity: 10
      },
      {
        id: 2, 
        store: "Store 2",
        quantity: 20
      }
    ]
  });

In order to manipulate this, you should pass the whole object and override the property you would like to update/change:

updateProduct({ ...product, name: "Product 1 - Updated" })

However, if you use "useImmer" you can send the only part you would like to change and immer itself will take care of the rest under the hood.

  const [product, updateProduct] = useImmer({
    name: "Product 1",
    SKU: "SKU-001",
    availability: 30,
    stock: [
      {
        id: 1, 
        store: "Store 1",
        quantity: 10
      },
      {
        id: 2, 
        store: "Store 2",
        quantity: 20
      }
    ]
  });

So to update:

updateProduct((draft) => { 
   draft.name = "Product Updated" };
})

It does make more sense when you are manipulating complex structure, let say if you want to change the second object in the "Stock" array, then you can use:

updateProduct((draft) => {
    draft.stock[1].quantity = 30;
})
Dharman
  • 30,962
  • 25
  • 85
  • 135
mexam
  • 435
  • 4
  • 14