React Hooks at a Glance
Tags: react, javascript
Published: 2021-02-11 13:12:46

---
title: React Hooks at a Glance
published: true
date: 2021-02-09 00:00:00 UTC
tags: react, javascript
canonical_url: https://www.mariokandut.com/how-to-use-react-hooks/
---

 **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**.

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.

[💰: Start your cloud journey with $100 in free credits with DigitalOcean!](https://m.do.co/c/29f238135b61)

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.

## [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#what-is-a-hook)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:

### [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#usestate)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.

### [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#useeffect)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>
  );
}
```

### [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#rules-of-hooks)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](https://www.npmjs.com/package/eslint-plugin-react-hooks).

## [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#tldr)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](https://www.twitter.com/mariokandut)**.

If you want to know more about **[React](https://www.mariokandut.com/tags/react)**, have a look at these [React Tutorials](https://www.mariokandut.com/tags/react).

References (and Big thanks):

[React Hooks Intro](https://reactjs.org/docs/hooks-intro.html#motivation), [ReactJS](https://reactjs.org/docs/hooks-overview.html), [Robin Wieruch](https://www.robinwieruch.de/react-hooks)