react icon indicating copy to clipboard operation
react copied to clipboard

[Question] question regarding best practice

Open EwanValentine opened this issue 9 years ago • 4 comments

Apologies for the none-standard git issue, but I wasn't quite sure where else to ask.

I'm working with another developer on a React project, using ES6. So I was just wondering, is there anything wrong or bad practice about using fat arrow functions hoisted, and parameters hoisted to a component class, which aren't set within the constructor? So for example...

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
  }

  state = {
    name: '',
  }

  setName = (e) => {
    this.setState({ name: e.target.value })
  }
}

My colleagues approach...

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      name: '',
    }

    this.setName = this.setName.bind(this)
  }

  setName(e) {
    this.setState({ name: e.target.value })
  }
}

The reason I use approach 1 is because it automatically scopes this within the function, so you don't need to write the additional line to bind a method within the constructor.

I figured ultimately this was down to preference as they both worth identically. But I've been told my way (first example) was bad practice.

Thanks in advance!

EwanValentine avatar May 21 '17 09:05 EwanValentine

The possibility to use the property initializer syntax is mentioned in the official documentation : https://facebook.github.io/react/docs/handling-events.html I guess it is not a bad practice otherwise it would have been pointed out. There is just a warning about the fact that it is experimental syntax, so in the end it is up to you to decide to use the dedicated babel plugin and enable this feature or notre.

rizoom avatar May 21 '17 11:05 rizoom

@EwanValentine On a side note, you don't need to pass in props in constructor and when calling the base class unless you don't need the props inside the constructor.

So,

constructor() {
    super()
    this.state = {  name: '' };
}

should do fine as well.

laumair avatar May 21 '17 18:05 laumair

Thanks folks! This is really helpful :)

EwanValentine avatar May 21 '17 21:05 EwanValentine

For future reference, we try to use this issue tracker for bug reports and feature requests only. If you have a usage or support question, we recommend checking out one of the great community-driven platforms like Reactiflux, discuss.reactjs.org, or StackOverflow!

aweary avatar Jun 05 '17 19:06 aweary