React Hooks is a feature proposal developed so you can access all the features used in classes from functional components.
The motivations for the Hooks feature proposal are the following ones:
The idea is to give power to functional components in the React ecosystem
.
Let’s imagine that we’re trying to write a Counter component
, the normal implementation would be the following one:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Counter extends Component {
state = {
count: 0,
};
increment = () => this.setState({ count: this.state.count + 1 });
decrement = () => this.setState({ count: this.state.count - 1 });
render() {
return (
<div className="App">
<button onClick={this.increment}>+</button>
<p>{this.state.count}</p>
<button onClick={this.decrement}>-</button>
</div>
);
}
}
ReactDOM.render(<Counter />, document.getElementById('root'));
The Hook
based implementation would be the following one:
import React, { memo, useState } from 'react';
import ReactDOM from 'react-dom';
const Counter = memo(() => {
const [count, setCount] = useState();
const increment = _ => setCount(count + 1);
const decrement = _ => setCount(count - 1);
return (
<div className="App">
<button onClick={increment}>+</button>
<p>{count}</p>
<button onClick={decrement}>-</button>
</div>
);
});
ReactDOM.render(<Counter />, document.getElementById('root'));
The benefits of using Hooks here a really clear:
There are two types of Hooks.
You can do it by creating a Code Sandbox. Install react@16.7.0-alpha.0
and react-dom@16.7.0-alpha.0
.
Or checkout and fork the Counter Demo here.
Checkout this post:
You can read more about hooks from here.
Some useful resources from Hooks: