Professional Development

Class properties versus Constructor in React

A simple counter component in React can look like this:

class Counter extends React.Component {
  constructor() {
    super();
    this.state = {counter: 0};
    this.handleClick = this.handleClick .bind(this);
  }
  handleClick() {
     this.setState({counter: this.state.counter + 1})
     console.log(this.state.counter);
  }
  render() {
    return (
      <button onClick={this.handleClick}>Click</button>
    )
  }
}

ReactDOM.render(<Counter />, document.querySelector("#app"))

The component initializes the state variable “counter” with the value zero and then updates it by one every time the button is clicked. See it working here.

This same code can be written much more cleanly using class properties instead of constructor properties, like so:

class Counter extends React.Component {
  state = {counter: 0};
  handleClick = () => {
     this.setState({counter: this.state.counter + 1})
     console.log(this.state.counter);
  }
  render() {
    return (
      <button onClick={this.handleClick}>Click</button>
    )
  }
}

ReactDOM.render(<Counter />, document.querySelector("#app"))

Notice how using the arrow function on handleClick supersedes the need to bind “this” to it. Working example is here.

There is no disadvantage to using the latter approach, except that is it less verbose, as far as I know.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s