Edgar
Edgar

Reputation: 6846

How to update state in hooks correctly

as I know State in hooks can be changed in two ways.1 setCount(count - 1), 2 setCount((prevCount) => prevCount - 1),But I don't understand when I need to use 1 and 2 ways?

Upvotes: 0

Views: 76

Answers (2)

Estus Flask
Estus Flask

Reputation: 222309

setCount(count - 1) could be used only if it were guaranteed that setCount is called synchronously, and count reflects current state. This happens almost never because this indicates that state initialization went wrong:

const [count, setCount] = useState(0);

if (count == 0)
  setCount(count - 1);

Otherwise state setter is usually called in callback functions that will access stale state from enclosing scope, which is a common problem for useState:

const [count, setCount] = useState(0);

useEffect(() => {
  setTimeout(() => {
    // count === 0 here, even if it was changed since then
    setCount(count - 1)
  }, 1000)
}, []);

The use of state updater function guarantees that fresh state is in use. State updates can be batched this way:

setCount(prevCount => prevCount - 1);
setCount(prevCount => prevCount - 1);

For the same reason this.setState should be used together with state updater instead of this.state in class components.

Upvotes: 1

lecstor
lecstor

Reputation: 5707

Basically, you don't want to do setCount(count - 1) as your update value is based on the existing state value.

By using setCount((prevCount) => prevCount - 1) you ensure that you are using the latest value of the state whereas the non-function version will, in some instances, use an out-of-date value.

On the other hand, when you don't care about the current value of the state it's fine to use setCount(7).

Upvotes: 0

Related Questions