skip to Main Content
const onClickButton = (color) => {
 }  
 
const onClickButton = (color) => () => {
 }

Can anyone please tell the basic difference between these 2 functions?

I was making a very simple page on which,on clicking a particular button,the color changes.
Now in this,I needed to create a function for onClick.
On using the 1st function, my code did not worked, but the 2nd function worked fine.

2

Answers


  1. The first one is a function that can be called directly. The second one is is a function that returns a function with that argument already utilized.

    So for the first one, whatever part of the code (likely whatever framework you are using) that is calling the handler would need to pass an intended argument value. For the second one, you provide the argument when you define it, and that argument cannot be changed in later calls.

    I’d have to test if you give it a variable and pass that as the argument, if it would update when that variable is updated.

    Login or Signup to reply.
  2. The second function is actually a function that returns a function.
    So in regular code the difference would be:

    const onClickButton1 = (color) => {
        // body
    };
    
    const onClickButton2 = (color) => () => {
        // body
    };
    
    onClickButton1(color); // the body is directly called
    
    const callback = onClickButton2(color);
    callback(); // calling the body
    

    So if you are using the second function like this:

    <button onClick={onClickButton2(color)} />
    

    you can use the second function instead by just adding inline an arrow function to react to the event

    <button onClick={() => onClickButton1(color)} />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search