Search code examples
reactjscoding-styleconventions

Ask about React: function of class convention


When do I use an arrow function?

class App extends Component {
        onButtonClick = event => console.log(click!)
} 

and, When do I use a function of the class?

class App extends Component {
        onButtonClick() {console.log(click!)}
} 

Solution

  • First let's differentiate them,

    Arrow functions do not require binding like normal functions.
    They have a cleaner syntax.
    They are not the standard way of coding in Reactjs.
    If only a single statement is part of arrow function that it returns, you can omit curly braces.

    Then, coming to usage... Arrow function can be used for in a event handler where a value should be passed to the function, like onClick=dothis(arg) To do this, you have to wrap the dothis function in another function like onClick=()=>dothis(arg), otherwise your event handler won't work as required.

    I recommend using normal functions because Arrow functions are not mentioned in the standard documentation of Reactjs.

    """I prefer sticking to the standards"""