BBV logo

What are Hooks on React and how you can benefit from them?

Jonatan Salas

24 October, 2018 - 2 min read

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:

  • Reusability of Stateful components logic
  • Reduce complexity from components
  • Entry point for specific optimizations

The idea is to give power to functional components in the

React ecosystem
.

Dan explaining React hooks


How can we use a Hook?

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:

  • Reduce code implementation, we pass from having a class based to only have a functional based component. This also means a reduction of bytes from bundle size.
  • Logic is now shareable, we have decoupled the logic not only for state creation, even for how the state updates.

Is there a Hook only to work with state?

There are two types of Hooks.

Basic

  • State → useState
  • Context → useContext
  • Side-Effects → useEffect

Additional

  • Refs → useRef
  • Callbacks → useCallback
  • Reducers → useReducer
  • Memoized Values → useMemo
  • Imperative Methods → useImperativeMethods
  • Mutation Effects → useMutationEffect
  • Layout Effects → useLayoutEffect

How can I test Hooks now?

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.


Interested to build a Todo App using Hooks?

Checkout this post:


Interested to know more about Hooks?

You can read more about hooks from here.

Some useful resources from Hooks:

Jonatan Salas

Co-Founder and CEO at BlackBox Vision.

Subscribe for latest updates

Sign Up for our newsletter and get notified when we publish new articles for free!

Maybe you could be interested to read