Search code examples
reactjsarrow-functions

When should we define a function inside a React class as arrow function?


I'm creating a web page using React. There is a textarea where we could input a text. Thus, inside return, onChange is linked to a function named inputChange:

<textarea value={this.state.text} onChange=...></textarea>

Regarding inputChange, one way is to define it as a method (called object method?):

inputChange (event) {
  let value = event.target.value;
  this.setState((s) => ({ ...s, text: value }));
}

Another way is to define it as an arrow function (called class property?):

inputChange = (event) => {
  let value = event.target.value;
  this.setState((s) => ({ ...s, text: value }));
}

(One thing I notice is that if we define inputChange as arrow function, we can see inputChange as a property of this, when we print this inside e.g., render.)

Does anyone know which way is be better? In general, when should we define a function inside a React class as arrow function?


Solution

  • Arrow functions come handy to tackle the problem of this in components. More often you would find yourself in situations when you are passing callback functions.

    Now, in these cases not using an arrow function might cause issues because you ca not be sure of the value of this everytime the call back functions are called.

    So a better approach is to use arrow functions instead. They preserve the value of this keyword inside the function as it was outside the function.

    This approach resolves a lot of unseen frustrating bugs around which could arise due to incorrect usage and value of keyword this

    For more detailed answers refer to this article for explanation using code snippets.