React: Constructor Bind vs Class Properties

When we get into React we might see some event handling with like this.handleClick = this.handleClick.bind(this); In fact, that was an example from one of React’s documentation. This ‘binding’ is called Constructor Bind, we can use another way to handle an event, by using Class properties.

Class properties eliminate the need to do binding on the Constructor of a class. Take for example the code from React’s event handling documentation:

class Toggle extends React.Component {
	constructor(props) {
		super(props);
		this.state = { isToggleOn: true };

		// This binding is necessary to make `this` work in the callback
		this.handleClick = this.handleClick.bind(this);
	}

	handleClick() {
		this.setState(state => ({
			isToggleOn: !state.isToggleOn
		}));
	}

	render() {
		return (
			<button onClick={this.handleClick}>
				{this.state.isToggleOn ? 'ON' : 'OFF'}
			</button>
		);
	}
}

ReactDOM.render(<Toggle />, document.getElementById('root'));

The documentation specifically wrote:

// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);

We can make this shorter using Class Properties, leveraging arrow functions in the class we can eliminate the binding of this on the constructor. Take the example above we can change it into:

class Toggle extends React.Component {
	state = { isToggleOn: true };

	handleClick = () => {
		this.setState(state => ({
			isToggleOn: !state.isToggleOn
		}));
	};

	render() {
		return (
			<button onClick={this.handleClick}>
				{this.state.isToggleOn ? 'ON' : 'OFF'}
			</button>
		);
	}
}

ReactDOM.render(<Toggle />, document.getElementById('root'));

The code seem simpler than when we use Constructor Binding. However there is a caveat when we choose to use Class Properties. The performance can be potentially worse than when we use Constructor Binding. Worse, but in most cases it might not matter much.

Some references:

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.