DEV Community

Discussion on: React Cheat sheet (Updated June 2021)

Collapse
 
charlotteisambert profile image
Charlotte Isambert • Edited

Thanks a lot that's very helpful!

There is one thing I don't understand in this part from 'setState functional form' though:

function Counter() {
  const [count, setCount] = useState(0)
  // Use a function to set State
  const increase = () => setCount(() => count + 1)
  return (
    <>
      <h1>Counter</h1>
      <p>{count}</p>
      <button onClick={increase} className='btn'> + </button>
      <button onClick={() => setCount(() => count - 1)} className='btn'> - </button>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

I don't understand why we'd use the functional update of setState without its count param: setCount(() => count - 1).

I would understand if we used the count param from setCount: setCount((count) => count - 1), to make sure we use the last count value

Am I missing something? :)

Collapse
 
axmachina profile image
AxMachina

Your version is accurate. The point of using functional form is to ensure you get the most current state value and not the stale one (as in the original version).