0

Say for example we have a useState hook like so:

const [isImportant, setIsImportant] = React.useState("Yes") 

How come setIsImportant() cannot be directly referenced to set a value. For example, setIsImportant cannot be directly called using onClick():

onClick={(setIsImportant("no")}

Instead it needs to be wrapped in another function:

onClick={() => setIsImportant("no")}

What is the difference between these two lines of code? Shouldn't they do the same thing?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • I figured it out. The issue here is that functions are called whenever they have () after the name. This is regardless of if the function is being passed to something. As a result you cannot pass a function with a parameter since that function would inherently include (). Therefore, the function needs to be wrapped in a function without parameters so it can be passed. Hence the anonymous function. – Jordan Tannen Sep 08 '22 at 23:55

0 Answers0