Search code examples
reactjsreact-hooksuse-state

React useState. Why do the docs advise passing a function with the previous state when setting the state?


In the React docs (https://reactjs.org/docs/hooks-reference.html#usestate) it says "If the new state is computed using the previous state, you can pass a function to setState" like so:

const [count, setCount] = useState(initialCount);
setCount(prevCount => prevCount + 1)

But why is React suggesting this as a solution when it can be done more succinctly using the count variable like so:

const [count, setCount] = useState(initialCount);
setCount(count + 1)

This latter approach works even when working with mutable objects like arrays as in this example:

https://codesandbox.io/s/6b-array-subcomp-event-usestate-props-r032xv


Solution

  • If you have a function that use SetCount twice, without using the prev state, it will setCount only once.

    const [count, setCount] = useState(0);
    const fun1 = () =>{
       setCount(count + 1)
       setCount(count + 1)
    }
    // it will change count to 1 rather than 2
    

    That's why it's recommended to use prev state