I read several entries with example codes in connection with React. For example, I'd just read a short article about Stateful and Stateless components with React. I saw a lot of "old way approaching" solution, so I would like to share with you a trick about the class based components and their state. You can use and try them with Create React App now!
The constructor things
You don't need to define constructor in a class based component just because of function bindings.
🌙 Old way:
constructor(props) {
super(props);
this.state = {
value: ""
};
this.handleChange = this.handleChange.bind(this);
}
```
**🌞New way:**
````javascript
class Test extends PureComponent {
constructor(props) {
super(props);
this.state = {
value: ""
};
}
const handleChange = () => {
// Handle change...
}
render() {
return(
<input value={this.state.value} onChange={this.handleChange} />
);
}
}
```
{% endraw %}
And this is not the end! The local state can be defined on the class level also:
{% raw %}
````javascript
class Test extends PureComponent {
state = {
value: ""
}
const handleChange = () => {
// Here comes the change things
}
render() {
return(
<input value={this.state.value} onChange={this.handleChange} />
);
}
}
```
With this solution, you don't need to use constructor and you don't need to bind functions with their name in it. It is question of taste, I know, but I think we can write clear and more readable code this way.
Arrow functions is evil. It's just adding more complication reading js code those days. I'll stick to constructor. However it's not old because you use arrow functions. Function != Arrows functions.