Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use useImmer vs useState?

When should you useState vs useImmer?

With the major overhaul of the react documentation, there has been more recommendations in the react documentation to utilize useImmer instead of useState for easier readibility it seems.

As someone that is still new to frontend coding, I am still somewhat confused as to when to useImmer over useState? I have read that it is best used with nested objects or arrays, should this be when useImmer is mainly used over useState, as with useImmer from what I have read, I can also safely mutate arrays and objects? Although not recommended to mutate arrays and objects with useState.

When to useState vs useImmer?

like image 777
Fallen Avatar asked Dec 16 '25 12:12

Fallen


1 Answers

You never need to use useImmer. It is not part of react, but another package that makes dealing with more complex state a bit easier.

If you already have the use-immer package installed, then you'd use useImmer when your state is an object or array, while using useState for simpler datatypes, such as string, number, and boolean.

For example:

const initialUser = {
  name: 'Luke Skywalker',
  friends: ['Han Solo', 'Chewy', 'Leia'],
};

const [count, setCount] = useState(0);
const [immerUser, updateImmerUser] = useImmer(initialUser);
const [stateUser, setStateUser] = useState(initialUser);

function inc() {
  setCount(count + 1);
}

function addImmerFriend(newFriendName) {
  updateImmerUser(draft => {
    draft.friends.push(newFriendName)
  })
}

function addStateFriend(newFriendName) {
  setStateUser({
    ...stateUser,
    friends: [
     ...stateUser.friends,
     newFriendName,
    ],
  })
}
like image 182
Joe Lissner Avatar answered Dec 19 '25 02:12

Joe Lissner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!