When to use functional update form of useState() hook, eg. setX(x=>x+1)

Normally when we need to update a state in a functional component, we do something like this:

function Example() {
    const [count, setCount] = React.useState(0);
    return (<div><p>You clicked {count} times</p>
                 <button onClick={() => setCount(count + 1)}>
                    Click me
                 </button>
            </div>);
}

When and why will we ever need to use the functional update form?

function Example() {
    const [count, setCount] = React.useState(0);
    return (<div><p>You clicked {count} times</p>
                 <button onClick={() => setCount(c=>c + 1)}>
                    Click me
                 </button>
            </div>);
}

Answer

Use the function form when the setter may close over an old state value.

For example, if an async request is initiated, and you want to update state after that’s done, the request that was made will have scope of the state as it was at the beginning of the request, which may not be the same as the most up-to-date render state.

You may also need to use the function form if the same state value was just updated, eg

setValue(value + 1);
// complicated logic here
if (someCondition) {
  setValue(value => value + 1);
}

because the second call of setValue closes over an old value.