0

Can someone explain why this code won't run properly with curly braces around prev + 1 in the increment function?

export default function Counter() {
  const [clickCount, setClickCount] = useState(0);

  useEffect(() => {
       document.addEventListener('mousedown', increment);
       return () => {
           document.removeEventListener('mousedown', increment);
      };
   });

   // your code here
  const increment = () => {
      setClickCount((prev) => {prev + 1})
  }

  return (
      <h1>Document Clicks: {clickCount}</h1>
  );
}
Dany
  • 1
  • 3
    Cause you missing `return`. it should be `setClickCount((prev) => {return prev + 1})`. – ulou Jul 18 '22 at 16:14

3 Answers3

1

Arrow function returns expression result by default, but only without that {}

If you want to use {} remember to add return: (prev) => {return prev + 1}

Konrad
  • 21,590
  • 4
  • 28
  • 64
0
 setClickCount((prev) => { return prev + 1})

you have to return a value for this to work

0

Either you use return statement for existing setClickCount or remove the arrow function and directly update the value.

 const increment = () => {
      setClickCount((prev) => {return prev + 1})
  }

or

const increment = () => {
      setClickCount(clickCount + 1)
  }

Jsfiddle link : https://jsfiddle.net/sureshpoosapati/85yhs4r1/1/

Suresh
  • 923
  • 1
  • 10
  • 21