4

I'm starting a new try to learn React (with an online-curse). But there is one question of understanding:

Sometimes i call a function with an Arrow-Function. Example: (shortend)

const [color, setColor] = useState();
<button onClick={()=>setColor('green)}>Green</button>

But sometimes I call a function just as... function?!

const handleChange = ({target}) => {
console.log(target.value);
}
<input onChange={handleChange} />

I tried to google it, but i can't get an answer to this question.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
peacemaker
  • 57
  • 4

2 Answers2

1

Event handlers like onChange and onClick pass the "onX" event to the attached handlers. Such is the case with onChange={handleChange} where handleChange clearly accepts the event and destructures target value.

const handleChange = ({target}) => {
  console.log(target.value);
}

Same as

const handleChange = (event) => {
  const { target } = event;
  console.log(target.value);
}

In other cases where the attached callback may not care to receive the event object, or the callback accepts a different argument then you'll see an anonymous function used, as is the case with the first snippet.

onClick={() => setColor('green')}

Here setColor is a state update function and we want to explicitly pass the value "green" to it. If you were to do onClick={setColor} then the click event object would be passed to the state updater and saved in state, which isn't the desired behavior.

You will also come across some code examples or code where some dev does:

onClick={(e) => myCallback(e)}

But as shown above, this can quite simply be expressed more directly as

onClick={myCallback}

The point I want to show here is that when the function signature of the callback matches the function signature of the handler that an anonymous function isn't necessary for the code to function properly. It is rather when there is a "mismatch" between them that a "proxy" function is necessary to mate the callback to the handler.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
0

Whenever you want to pass the arguments explicitly you can use the below approach,

<button onClick={()=>setColor('green)}>Green</button>

In case you don't want to pass any arguments, then you can just provide the function for the onclick handler,

const handleClick = () => {
   // logic here
  }

<button onClick={handleClick}>Green</button>
Sarun UK
  • 6,210
  • 7
  • 23
  • 48