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
Dan explaining React hooks
Let’s imagine that we’re trying to write a
, the normal implementation would be the following one:Counter component
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
based implementation would be the following one:Hook
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
andreact@16.7.0-alpha.0
.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:
Subscribe for latest updates
Sign Up for our newsletter and get notified when we publish new articles for free!