React Nugget #2: Why do I love React Hooks?

By Vijay Thirugnanam

There are lot of reasons to love React Hooks. But I have one reason that stands out from the rest.

Consider a class component that sets some state. This component has a controlled input within it.

class MyInput extends Component { state = { text: '' }; render() { <input type="text" value={text} onChange={..} /> }
}

With class components there are three ways to write onChange handler.

#1: Use bind in constructor

The standard and safest way is to bind this in the constructor like so.

class MyInput extends Component { state = { text: '' }; constructor() { super(); this.handleChange.bind(this); } handleChange(e) { this.setState({ text: e.target.value }); } render() { return <input type="text" value={text} onChange={this.handleChange} /> }
}

#2: Use bind within onChange prop

Using bind within onChange prop creates a new function and has a slight performance implication when multiple inputs are around. The advantage of using this coding pattern is to avoid writing the constructor function.

class MyInput extends Component { state = { text: '' }; handleChange(e) { this.setState({ text: e.target.value }); } render() { return <input type="text" value={text} onChange={this.handleChange.bind(this)} /> }
}

#3: Use arrow function

Using arrow function avoids creating new functions by calling bind repeatedly. However, there are times when we need to pass an extra parameter. In those cases, we cannot use bind because we cannot use bind with arrow functions.

class MyInput extends Component { state = { text: '' }; handleChange = (e) => { this.setState({ text: e.target.value }); } render() { return <input type="text" value={text} onChange={this.handleChange} /> }
}

This coding pattern also requires more babel transforms. Not a big problem but something that developers should be aware of.

Why I love React Hooks

And why do I love React hooks? We do not deal with the messy ES6 class and deal with nested functions and closures. Here is how the same code looks with React hooks.

function MyInput() { const [text, setText] = useState(''); function handleChange(e) { setText(e.target.value); } return ( <input type="text" value={text} onChange={handleChange} /> );
}

With React Hooks, I do not need to deal with the messy “this” coding pattern of class components. And there are no three ways to write this code.

I had the same feeling when I don’t have to use C++ pointers when using C#.

React Nugget #2: Why do I love React Hooks?