Recently a new proposal have been released to the ReactJS community – for React Hooks.
Roughly, the React Hooks are new ways to utilize the react features, that were previously available only via the JS class syntax.
I cannot hide my excitement for the hooks because they:
- Simplify the code that is written
- Make the new JS classes non-mandatory, which makes it a bit easier to start working with React for veteran developers (like ones coming from jQuery / old vanilla JS / WordPress background)
- Help organize the code together.
Something I didn’t like was the specific, that updating state from the render function is going to run the render again after it completes. This is the case where I’d prefer to use the lifecycle methods instead.
After working with React, one inevitably starts using event listeners, which in a class component forces them to have a constructor where the event handlers are bound to the “this”:
class MyComponent {
constructor () {
this.onConfirm = this.onConfirm.bind( this );
this.onDecline = this.onDecline.bind( this );
}
render () {
let otherComponents = []; // ...
return (
<div>
{ otherComponents }
<button onClick={ this.onConfirm }>Confirm</button>
<button onClick={ this.onDecline }>Decline</button>
</div>
);
}
onConfirm () { ... }
onDecline () { ... }
}
I’m more than happy that the time of binding these is now gone!