Pavlos Karalis
Pavlos Karalis

Reputation: 2966

Is it best practice to pass a state prop into an onClick function?

Does it make a difference? My guess is yes in maintaining accuracy based on how setProp can pass a function, but I can't locate an answer in docs.

  const [prop, setProp] => useState(value);

  const myFunction = (param) => {
    console.log(param)
  }

  return (
    <div onClick={()=> myFunction(prop)}></div>
  )

vs

  const [prop, setProp] => useState(value);

  const myFunction = () => {
    console.log(prop)
  }

  return (
    <div onClick={myFunction}></div>
  )

Upvotes: 3

Views: 441

Answers (2)

Yousaf
Yousaf

Reputation: 29281

There is one main difference between both code examples.

In first code example, 2 functions get created on every re-render

  • anonymous function passed to onClick prop
  • myFunction

whereas in second code example, only 1 function is created, i.e. myFunction

Other than that, there's no difference because in any particular render of the component, value of prop won't change. So it makes no difference whether you pass is as an argument or you access it directly from inside the myFunction.

As a side note, you should choose a different name for state variable because it could be confused with props object.

Upvotes: 1

Adrian Pascu
Adrian Pascu

Reputation: 1039

In my opinion the second approach is better. Other that what Yousaf mentioned, there is no performance difference, but it keeps your code cleaner. Obviously, sometimes you need to use the first approach to pass some parameters to your function or something like that

Upvotes: 1

Related Questions