1

I am learning React an encountered two different ways of writing event handling functions and do not know if they are somehow semantical identically or if it is just different sytax?

This seems more intuitive for me:

clickHandler = () => {
  this.setState({
    random: Math.random(),
  });
};

But in the book I am using they always do something like this:

clickHandler2() {
  return () => {
    this.setState({
      random: Math.random(),
    });
  };
}

I created a CodePen and all the behavior seems the same, especially this binding. Is it just different syntax for the complete same behavior?

1
  • 1
    Yes, it's just a different syntax. I prefer the first option because of reading reasons. Commented Nov 12, 2020 at 10:35

1 Answer 1

3

In some way it is different syntax, but second example where you return function back after executing clickHandler2() that is something called Curry function and you can see more about that here in this article.

Main benefit for clickHandler2() approach is that you can parametrize return function that will be executed when onClick occurs. This is good when you are looping through items and you need to pass some data (ex. id) if that code depends on any data.

clickHandler2(id) {
  return () => {
     doSomething(id);
  };
}
userIds.map((id) => <button onClick={this.clickHandler2(id)}>Click2</button>);

This is usually a case in lists. Other way for this to happen without using Curry function is to do this:

clickHandler = (id) => {
  dosomething(id);
};
userIds.map((id) => (
  <button
    onClick={() => {
      this.clickHandler(id);
    }}
  >
    Click2
  </button>
));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.