---
title: "Overview of React Hooks"
description: "Learn what's new with React Hooks. For example, use state in a functional component."
authors:
  - name: "Kapehe Jorgenson"
    url: "https://auth0.com/blog/authors/kapehe-jorgenson/"
date: "Feb 6, 2019"
category: "Developers,Whats New,React"
tags: ["react-hooks", "react"]
url: "https://auth0.com/blog/overview-of-react-hooks/"
---

# Overview of React Hooks



**TL;DR:** - In this article, we are going to go over React Hooks. This new feature is currently in the React 16.8 stage. With React Hooks, we will be able to write functional components that have a state; no need to use a class component for state anymore!

## React Hooks

[React](https://reactjs.org/) is constantly giving us cool new updates. Currently, in React 16.8, we have [React Hooks](https://reactjs.org/blog/2019/02/06/react-v16.8.0.html)! What if I told you Hooks got rid of the major need for class components? This new feature may make your code more concise. Don’t we all want that?

But what is all the fuss with React Hooks? Why should I stop using class components? By all means, no need to stop using them. There is no plan to get rid of class components and if the developer wants to, the transition to switch to React Hooks is going to be seamless.

<include src="TweetQuote" quoteText="React Hooks can make code more concise and gets rid of the need to use class components for state."/>

## What Is a "Hook"?

React Hooks are a way to "hook" into a functional component. Functional components have never been able to hold a `state`, but with Hooks, it gives them the power to do so now.

<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">Learn all about Hooks from our keynote (me and <a href="https://twitter.com/sophiebits?ref_src=twsrc%5Etfw">@sophiebits</a>) and a deep dive by <a href="https://twitter.com/ryanflorence?ref_src=twsrc%5Etfw">@ryanflorence</a>! <a href="https://t.co/bGk9ajVtgi">https://t.co/bGk9ajVtgi</a></p>&mdash; Dan Abramov (@dan_abramov) <a href="https://twitter.com/dan_abramov/status/1055863985298423808?ref_src=twsrc%5Etfw">October 26, 2018</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

If we were to head over to [React docs on Hooks](https://reactjs.org/docs/hooks-intro.html), they said it best with:

> Hooks are an upcoming feature that lets you use state and other React features without writing a class. [Source](https://reactjs.org/docs/hooks-intro.html)

`State` is written in a much cleaner way and setting or updating that `state` can be declared in as little as one line. 

Then you have [lifecycle methods](https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class) like `componentDidMount` or `componentDidUpdate` that will be taken care of by [`useEffect`](https://reactjs.org/docs/hooks-effect.html). Hooks are powerful, and it allows for functional components to harness that power.

<include src="TweetQuote" quoteText="React Hooks are a way to 'hook' into a functional component."/>

## Using React Hooks in Projects

Now that we have a basic understanding of what React Hooks are, are we ready to use it in our projects? To get the current version of React into your project and start using React Hooks, simply run this command in your IDE:

```bash
npm install -S react@16.8 react-dom@16.8
```

## What State Looks Like Currently

In a class component, we are able to declare [`state`](https://reactjs.org/docs/state-and-lifecycle.html#adding-local-state-to-a-class) and set that state with [`setState`](https://reactjs.org/docs/state-and-lifecycle.html#using-state-correctly) We are familiar with it looking something like this:

```javascript
// 24 lines of code

import React from "react";
import ReactDOM from "react-dom";

class ClassExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      phrase: "My Favorite Color Is "
    };
  }

  render() {
    return (
      <div>
        <p>{this.state.phrase}</p>
        <button onClick={() => this.setState({ phrase: this.state.phrase + "Blue" })}>
          Reveal the Color!
        </button>
      </div>
    );
  }
}

ReactDOM.render(<ClassExample />, document.getElementById("root"));
```

[The CodeSandbox for the above code can be found here.](https://codesandbox.io/s/k5jl7v0wrv)

In this example, we are declaring our `state` to be the phrase, `"My Favorite Color Is "`. We then create a button that when clicked, activates the `setState` and adds on the string, "Blue" to the phrase.

The output of this component would look like this:

![The output of a class component using state and setState](https://images.ctfassets.net/23aumh6u8s0i/6otb0DYExnm9O5T9OMQMj4/8765d9b3205cc937f857db0e71ca89f8/class-component)

And once the button is clicked, we should see this:

![The output of a class component when the button is clicked and setState is used](https://images.ctfassets.net/23aumh6u8s0i/20NvLYOlSlPaFXoGMN27GL/143462f87fd376754530414ed3ff1461/class-component-setState)

## What State Can Look Like With React Hooks

If we took that same logic from the class component, put it into a functional component, and used React Hooks instead, we could cut out a lot of lines of code. Let’s see how that would look like.

```javascript
// 17 lines of code

import React, { useState } from "react";
import ReactDOM from "react-dom";

function HooksExample() {
  const [phrase, setPhrase] = useState("My Favorite Color Is ");

  return (
    <div>
      <p>{phrase}</p>
      <button onClick={() => setPhrase(phrase + "Blue")}>
        Reveal the Color!
      </button>
    </div>
  );
}

ReactDOM.render(<HooksExample />, document.getElementById("root"));
```

[The CodeSandbox for the above code can be found here.](https://codesandbox.io/s/3x54vv31rq)

We see here that `state` looks different, much different. Besides the keyword `useState`, we don’t even see `state` being used at all.

In this line:

```javascript
const [phrase, setPhrase] = useState("My Favorite Color Is ");
```

This is where our state is being set. The two values, `phrase` and `setPhrase` are placeholders. We also see a new feature, `useState`.

1. `phrase` is equal to `this.state`.
2. `setPhrase` is equal to  `this.setState`.
3. `useState` is going to be our initial state value.

By using `setPhrase` within the React element being rendered, we are able to set a new state value and reveal the favorite color after the button is clicked.

The difference in the number of lines between these two examples is seven lines, but that can grow so much depending on your component. But the big difference is that we now can declare our state in a single line! We are able to replace our class constructor for a single function call.

By looking at `useState` a little more, this is the Hook that allows for the us to add in state to our functional component. You can read more about that in the [React docs here!](https://reactjs.org/docs/hooks-state.html#whats-a-hook)

Also, notice that in the Hooks example, it was a functional component. Using `state` in a functional component, who would have thought!

## Why the Square Brackets?

This is using the JavaScript syntax, ["array destructuring"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). Array destructing is when we are able to "unpack" values from an array and assign them to variables.

We are able to give the variables our own names, like `phrase` and `setPhrase` and then the `useState` knows that those two values are what it's going to be using. Once setting those two variables, the `useState` will be able to map over the values and know that the first value has the name of `phrase` and the second value has a name of `setPhrase`.

```javascript
const [firstvalue, secondvalue] = useState(0);
```

## Multiple State Hooks

Want to use more than just one state hook in a component? React allows for [multiple state hooks](https://reactjs.org/docs/hooks-state.html#tip-using-multiple-state-variables) in one component:

```javascript
function LotsOfStates() {
  const [name, setName] = useState("Sarah");
  const [color, setColor] = useState("Blue");
  const [shopping, setList] = useState([{ item: "Almond Milk" }]);
```

We are able to give different names to particular `states`, that way things are kept organized. Rather than using the word, `state`, we give it a name like, `color` or `shopping` so we know exactly which one we are working with.

## The Effect Hook

Another neat feature of React Hooks is the use of [`useEffect`](https://reactjs.org/docs/hooks-effect.html). This will handle the lifecycle methods that we would want to use in our React code. The following code is based on an example presented in the React docs:

```javascript
import { 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>
  );
}
```
[Source](https://reactjs.org/docs/hooks-effect.html)

The `useEffect` hook replaces the following lifecycle methods: 

1. `componentDidMount` 
2. `componentDidUpdate`
3. `componentWillUnMount`

In a sense, it combines the power of these three, and makes one mega lifecycle method! 

The Effect Hook tells the component what we would like it to do at a certain time. After render, it will take care of any logic within the `useEffect` function. It could be something like the React docs example above or even to fetch data from an API.

<include src="asides/AboutAuth0" />

## Conclusion

In conclusion, when using React Hooks, be sure to follow the [docs](https://reactjs.org/blog/2019/02/06/react-v16.8.0.html)

Class components are not going anywhere. Although, now we have this awesome, more concise way to write state in function components, rather than going between class and function.

Thanks for reading! 
