Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between useState and useImmer?

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?

like image 309
randombits Avatar asked Jan 26 '23 02:01

randombits


1 Answers

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;
})
like image 80
mexam Avatar answered Feb 23 '23 20:02

mexam