React Next 2019: React Hooks – the main uses

Share This Post

On June 12 of this year, part of the Apiumhub Frontend team had the opportunity to attend the React Next 2019 conference in Tel Aviv, a conference focused mainly on React and React Native. There we had the opportunity to attend very interesting talks about React frameworks, optimization and performance improvement of the React code, SEO with a SPA and many others.

The talk that caught my attention was “Modern React – The Essentials” by Liad Yosef, in which he explained the latest React news, such as React Hooks, concurrent mode, suspense, lazy.
Personally, I was very interested in the use of React Hooks, and how this could change the development of React, so I will explain the main uses of Hooks in this article.

 

React Next 2019: React Hooks – the main uses

 

useState hook

We will start by looking at a traditional React class, we have created a dropdown that is formed by a button that will execute the state toggle to show or hide our list of items:


  export default class Dropdown extends Component {
  constructor() {
    super();
    this.state = { isDropdownvVisible: false };
    this.handleClick = this.handleClick.bind(this);
  handleClick() {
    this.setState(() => {
      return { isDropdownvVisible: !this.state.isDropdownvVisible };
    });
  }
  render() {
    const { isDropdownvVisible } = this.state;
    return (
      <div>
        <button onClick={this.handleClick}>Toogle dropdown</button>
        { isDropdownvVisible &&
            <ul>
                <li>First item</li>
                <li>Second item</li>
                <li>Third item</li>
              </ul>
      </div>
    );
  };
}

sandbox

In the following example we can see that when you click on the button we will execute the “handleClick” function that will change the value of the “isDropdownvVisible” state variable, so the list of html will react to this change and will show or hide the list based on the value of said variable.

  Formik vs React Hook Form

Although it works correctly we can see how we have to write a lot of code to execute a simple toogle of a Boolean. To solve this, React offers us the possibility of using Hooks.

Using hooks allows us to use functions and still have status variables, which saves us all the verbosity involved in using a class.

For this we will use the “useState” function of React.

import React, { useState } from "react";

The imported one we will use as follows:

const [isDropdownvVisible, toogleDropdownVisibility] = useState(false);

 

First, we will define an array that contains two variables:

  • Value: The name of the state variable that we want to define. In our case it will be called “isDropdownVisible”.
  • ModifierFunction: The name of the function that will modify our status. In our case it will be called “toogleDropdownVisibility”.

Also within the “useState” function we can define the initial value of our variable. In our case it will begin to be false.

Rewriting the previous code using hooks instead of classes would look like this:


export default function Dropdown() {
  const [isDropdownvVisible, toogleDropdownVisibility] = useState(false);
  function handleClick() {
    return toogleDropdownVisibility(!isDropdownvVisible)
  }
  return (
      <div>
        <button onClick={handleClick}>Toogle dropdown</button>
        { isDropdownvVisible &&
            <ul>
                <li>First item</li>
                <li>Second item</li>
                <li>Third item</li>
              </ul>
      </div>
    );
}

sandbox

 

useEffect hook

In addition to allowing us to have a state without forcing us to use classes, the hooks offer us a multitude of possibilities, one of the most outstanding is the “useEffect” function that allows us to do side effects within our function. 

Using `useEffect` we notify React that we want the function we pass as a parameter to be executed in each render (by default), which saves us depending on lifecycle methods such as  “componentDidUpdate”, “componentWillUnmount”, etc.

  Mobile insight for 4YFN & Mobile World Congress 2018

Let’s see an example using the component we have defined above:


import React, { useEffect, useState } from "react";
export default function Dropdown() {
  const [isDropdownvVisible, toogleDropdownVisibility] = useState(false);
  function handleClick() {
    return toogleDropdownVisibility(!isDropdownvVisible)
  }
  useEffect(() => {
    console.log(isDropdownvVisible);
  })
    return (
      <div>
        <button onClick={handleClick}>Toogle dropdown</button>
        { isDropdownvVisible &&
            <ul>
                <li>First item</li>
                <li>Second item</li>
                <li>Third item</li>
              </ul>
      </div>
    );
}

Running the previous code we can see how in each render of the component be will shown the value of the “isDropdownvVisible” variable.

In this case, we will not have any problem, since it is a simple logging of data, but what would happen if we wanted to make a http request when the value changed, would we have to do it in each render?
To avoid this we can pass a second parameter to the “useEffect” function formed by an array with the value that we want to compare, and unless it is different, the function that we have defined as the first parameter of “useEffect” will not be executed.

  useEffect(() => {
    console.log(isDropdownvVisible);
  }, [true])

 

In this case, it will only show us the value when it is “false”.

We have already seen how to use the hook of effects to encapsulate our logic, so we can create our own hooks to share functionalities between different components, such as data fetch, data parsing, etc.

This allows us to create our services and share them very quickly and cleanly.

 

React Next: React Hooks conclusion

As a conclusion for the use of Hooks, it offers us a radical change in the creation of our components and services, since we have gone from using classes to being able to use functions with internal status and we saved the entire “boilerplate” to implement all the flow of the Lifecycle of React using “useEffect”, so once these improvements are commented, you just have to try to adapt our code to the use of Hooks and enjoy it!

  Domain Driven Design Distilled by Vaughn Vernon

 

If you found this article about React Next interesting, subscribe to our monthly newsletter

Author

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Subscribe To Our Newsletter

Get updates from our latest tech findings

Have a challenging project?

We Can Work On It Together

apiumhub software development projects barcelona
Secured By miniOrange