React Hooks at a Glance
© https://reactjs.org/

React Hooks at a Glance

How to use React Hooks

By Mario Kandut

Hooks are a new addition in React 16.8 and were first presented at the React Conf in 2018, as a way to manage state and side effects in functional components. Before 2018 function components were more or less stateless, but this has changed since.

React Hooks let you use state and other React features without writing a class. Hooks are also backwards-compatible.

💰 Start your cloud journey with $100 in free credits with DigitalOcean.

Hooks solve a wide variety of problems:

  • Reuse Stateful Logic: It’s hard to reuse stateful logic between components. Hooks allow you to reuse stateful logic without changing your component hierarchy.
  • Complex components: Complex components become hard to understand. Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data).
  • Classes can present unintentional patterns: Classes confuse both people and machines and can introduce unintentional patterns that make these optimizations fall back to a slower path. Classes don’t minify very well, and they make hot reloading flaky and unreliable. Hooks let you use more of React’s features without classes.

Hooks work side-by-side with existing code. A gradual adoption strategy is possible.

React will keep supporting class components for the foreseeable future. Facebook has tens of thousands of components written as classes, and there are absolutely no plans to rewrite them.

What is a Hook?

Hooks are functions that let you hook into React state and lifecycle features from function components. Hooks don’t work inside classes. You don't need a class.

React provides a few built-in Hooks like useState. You can also create your own Hooks to reuse stateful behavior between different components.

Let's take a brief look at the built-in Hooks useState and useEffect first:

useState

Let's start with the example from the official docs, a simple counter, once build with Class and once with Hooks.

Class

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button
          onClick={() =>
            this.setState({ count: this.state.count + 1 })
          }
        >
          Click me
        </button>
      </div>
    );
  }
}

The state starts as { count: 0 }, and we increment state.count when the user clicks a button by calling this.setState().

useState Hook

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

The only argument to useState is the initial state. In the example above, it is 0 because our counter starts from zero. Note that unlike this.state, the state here doesn't have to be an object — although it can be if you want. The initial state argument is only used during the first render.

useEffect

Side effects or simply effects like data fetching, subscriptions or manually changing the DOM from React components can't be performed during rendering.

The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API.

Hooks can also be combined. Let's say you want to change the document.title in the counter example from above on every change on count.

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

Rules of Hooks

React Hooks are just JavaScript functions, but they impose two additional rules:

  • Hooks should only be called at the top-level, never inside loops, conditions, or nested functions.
  • Only call Hooks from React function components, or your own custom Hooks. Don’t call Hooks from regular JavaScript functions.

To enforce this rules automatically, there is a linter plugin.

TL;DR

  • React Hooks make function components stateful without the need of a class.
  • Hooks remove complexity and work side-by-side with existing code.

Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut.

If you want to know more about React, have a look at these React Tutorials.

References (and Big thanks):

React Hooks Intro, ReactJS, Robin Wieruch

Newsletter Signup

Never miss an article.

Scroll to top ↑

Latest REACT articles: