skip to Main Content

Given the below react component.

function App() {
    const [text, handleTextChange] = useState('Some Text');

    const handleChange = () => {
        handleTextChange('Button handler clicked');
    }       

    return (
       <>
        <span>{text}</span>
        <button onClick={handleChange}>Change Text</button>
       </>
    )
}

In the above component we can write onClick handler in two different ways

<button onClick={handleChange}>Change Text</button>

and

<button onClick={() => handleChange()}>Change Text</button>

which approach is better and why ?

2

Answers


  1. Both will work, and in this case, both will functionally be pretty much the same.

    In your first example, you’re directly passing the function reference to onClick

    <button onClick={handleChange}>Change Text</button>
    

    In your second example, you’re passing an anonymous function to onClick. When called, that anonymous function calls handleChange

    <button onClick={() => handleChange()}>Change Text</button>
    

    Unless you’re getting some parameters passed to handleChange that you don’t want to, I’d suggest not wrapping it in an anonymous function like your second example. There’s no benefit to it. It’s just overhead.

    Login or Signup to reply.
  2. In the 2nd example you’re creating 2 functions, we usually would want that in case we want to pass dynamic data to the inner function.

    For example

    In this example we are passing a function reference:

    function App() {
        const handleChange = (event) => {
            // You have access to the click event object
            handleTextChange('Button handler clicked');
        }       
    
        return (
           <>
            <span>{text}</span>
            <button onClick={handleChange}>Change Text</button>
           </>
        )
    }
    

    But lets say you want to add a dynamic data, for example when iterating over a loop and you want to pass the index of each item:

    function App() {
      const [text, handleTextChange] = useState('Some Text');
    
      const handleChange = (event, item) => {
        // we have access to both the event object and the specific item in the list
      };
    
      return items.map(item => {
        return (
          <div key={item}>
            <span>{text}</span>
            <button onClick={event => handleChange(event, item)}>
              Change Text
            </button>
          </div>
        );
      });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search