useState: Updating state with callback function

useState: Updating state with callback function

This is from the React II Hooks lesson concerning updating state with a callback function. I understand why, but confused by the following example. Where does prevCount get initialized with the current state?

import React, { useState } from 'react';
 
export default function Counter() {
  const [count, setCount] = useState(0);
 
  const increment = () => setCount(prevCount => prevCount + 1);
 
  return (
    <div>
      <p>Wow, you've clicked that button: {count} times</p>
      <button onClick={increment}>Click here!</button>
    </div>
  );
}

Have a look at this post. If you still find something confusing, share your thoughts.

https://discuss.codecademy.com/t/faq-the-state-hook-set-from-previous-state/535828/43

Again thanks. This would have been a great addition to the that lesson. :slightly_smiling_face:

1 Like