Hooks - set from previous state

the course link is thishttps://www.codecademy.com/courses/react-101/lessons/the-state-hook/exercises/set-from-previous-state

I am not sure about one word of the following code:

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>
  );
}

when we define the increasement, why do we use prevCount instead of count, compared with setCount, count is the previous one, meanwhile, we does not define what prevCount is.

You passed an arrow function to setCount(), so the prevCount name is just the parameter name of the function to make it clear what it is receiving (it could have been named anything). setCount() calls the function with the latest value of count and whatever the arrow function returns is what will become the new value of count.

setCount() can accept a value, such as a simple count + 1, or it can accept a function like in the above code. As you continue in the course, it will touch on the benefits of each.

1 Like

Thank you so much for your answer!