17

Overview of React Hooks

 5 years ago
source link: https://www.tuicool.com/articles/hit/FVzmYb7
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

TL;DR:- In this article, we are going to go over React Hooks. This new feature is currently in the alpha 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!

Table of Contents

  1. Using React Hooks in Projects
  2. What State Looks Like Currently
  3. What State Can Look Like With React Hooks
  4. Why the Square Brackets

React Hooks

React is constantly giving us cool new updates. Currently, in React v16.8.0-alpha.1, we have React Hooks! 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.

"React Hooks can make code more concise and gets rid of the need to use class components for state."

TWEET THIS feuuMfj.png!web

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.

Learn all about Hooks from our keynote (me and @sophiebits ) and a deep dive by @ryanflorence ! https://t.co/bGk9ajVtgi

— Dan Abramov (@dan_abramov) October 26, 2018

If we were to head over to React docs on Hooks , they said it best with:

Hooks are an upcoming feature that lets you use state and other React features without writing a class. Source

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 like componentDidMount or componentDidUpdate that will be taken care of by useEffect . Hooks are powerful, and it allows for functional components to harness that power.

"React Hooks are a way to 'hook' into a functional component."

TWEET THIS feuuMfj.png!web

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:

npm install -S [email protected] [email protected]

What State Looks Like Currently

In a class component, we are able to declare state and set that state with setState We are familiar with it looking something like this:

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

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:

6rIFnea.png!web

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

jEFVRfi.png!web

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.

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

If using your own codesandbox.io account and starting fresh, be sure to update your react and react-dom to the 16.8.0-alpha.1 version.

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:

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!

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

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 in one component:

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

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

The useEffect hook replaces the following lifecycle methods:

componentDidMount
componentDidUpdate
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.

About Auth0

Auth0, a global leader in Identity-as-a-Service (IDaaS), provides thousands of enterprise customers with a Universal Identity Platform for their web, mobile, IoT, and internal applications. Its extensible platform seamlessly authenticates and secures more than 1.5B logins per month, making it loved by developers and trusted by global enterprises. The company's U.S. headquarters in Bellevue, WA, and additional offices in Buenos Aires, London, Tokyo, and Sydney, support its customers that are located in 70+ countries.

For more information, visithttps://auth0.com or follow @auth0 on Twitter .

Conclusion

In conclusion, React Hooks are still in the alpha stage. When using this feature, be sure to follow the docs as React finalizes this version.

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!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK