0
0
Reactframework~3 mins

Why Passing arguments to handlers in React? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if one simple trick could make your event handlers smarter and your code cleaner?

The Scenario

Imagine you have a list of buttons, and each button should do something different when clicked. You try to write separate functions for each button or use complicated code to figure out which button was clicked.

The Problem

Manually checking which button was clicked or writing many similar functions is slow, confusing, and easy to mess up. It makes your code bulky and hard to change later.

The Solution

Passing arguments to handlers lets you write one simple function that knows exactly what to do based on the argument it receives. This keeps your code clean and easy to understand.

Before vs After
Before
function handleClick(event) {
  if (event.target.id === 'btn1') {
    // do action 1
  } else if (event.target.id === 'btn2') {
    // do action 2
  }
}
After
function handleClick(id) {
  // do action based on id
}

<button onClick={() => handleClick('btn1')}>Button 1</button>
What It Enables

You can create flexible, reusable event handlers that respond differently depending on the input, making your app smarter and easier to build.

Real Life Example

Think of a shopping cart where each product's "Add to Cart" button sends the product ID to the same function, so you don't need a new function for every product.

Key Takeaways

Manual event handling for many elements is confusing and error-prone.

Passing arguments to handlers simplifies your code and makes it reusable.

This approach helps build dynamic and maintainable React apps.