DEV Community

Guilherme Toti
Guilherme Toti

Posted on

The right way to use function as parameter

Hey guys! How are you doing? Hope doing well!

I was answering few questions at Stack Overflow and I've just answer one that I believe is good to share as it is a bit complicated for beginners.

The situation

Let's imagine you have a list of items and you have a button for each item to delete it and this function receives the item id as parameter.

Lets imagine this is your Item Component:

const Item = ({ id, name, handleDelete }) => (
  <div>
    <p>{name}</p>
    <button>Delete</button>
  </div>
)
Enter fullscreen mode Exit fullscreen mode

It already receives everything you need, you have the id and you have the handleDelete function, that does something with this id.

But what is the right way to use the handleDelete function on the button's onClick, considering you need to pass the id as props?

The wrong way

Many of you may think that this is how to do that:

const Item = ({ id, name, handleDelete }) => (
  <div>
    <p>{name}</p>
    <button onClick={handleDelete(id)}>Delete</button>
  </div>
)
Enter fullscreen mode Exit fullscreen mode

But this is not!

If you use like that, what will happen is: as soon as the Component be rendered, it will execute the handleDelete function, because in this case, you are executing it, not passing it!

It should work if it doesn’t receives a parameter, as this example below:

const Item = ({ name, handleDelete }) => (
  <div>
    <p>{name}</p>
    <button onClick={handleDelete}>Delete</button>
  </div>
)
Enter fullscreen mode Exit fullscreen mode

There are many situations that you will use functions without parameters, and for those situations that's right to do this!

The solution

The solution is pretty simple! All you need to do is wrap your handleDelete function inside another function!
Check it out:

const Item = ({ id, name, handleDelete }) => (
  <div>
    <p>{name}</p>
    <button onClick={() => handleDelete(id)}>Delete</button>
  </div>
)
Enter fullscreen mode Exit fullscreen mode

Now it works perfectly! πŸŽ‰

Why?

The reason to do this is simple. When you wrap your function inside another function, you are passing to onClick a function as parameter, not executing it. The same as the previous example, a function without parameter, just a function.

Another way to do that, maybe it's more clear to you to understand is:

const Item = ({ id, name, handleDelete }) => {
  const onDelete = () => handleDelete(id)

  return (
    <div>
      <p>{name}</p>
      <button onClick={onDelete}>Delete</button>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Can you see what happened there?

I just created a variable to hold the function and passed this variable to onClick.

Maybe it's more clear now, right?

That's all folks!
I hope you guys enjoy it, and keep learning!

Top comments (0)