DEV Community

Cover image for React Hooks: An Introduction
Adriana DiPietro
Adriana DiPietro

Posted on

React Hooks: An Introduction

In a previous post, I introduced the concept of the React Lifecycle and its methods. We utilize these methods to portray the mounting and unmounting of components onto the DOM. While lifecycle methods do a great job of achieving this goal, there is a much newer and efficient methodology.

This methodology is called "Hooks". Prior to hooks, developers were required to use class components to portray the lifecycle. With the implementation of hooks, we may now use functional components.

What are Hooks?

Simply, Hooks are regular JavaScript functions.

Why use Hooks instead?

As both methodologies are used and accepted, there is no strong rule to switch over from using class components to hooks.

However, from a personal view, there are some benefits. In the ongoing attempts to DRY our code, hooks help because:

  1. Hooks allow you to reuse state and other behavior.
  2. Hooks require less boilerplate code.
  3. Hooks break our functional component into smaller and more powerful pieces.
  4. Hooks allow you to use state in React components without using class syntax.

Let's take a look at some code.

Some React Hooks

useState()

React offers a new way to declare initial state within a component.

function Categories(props){
    const [categories, setCategories] = useState([])
}
Enter fullscreen mode Exit fullscreen mode

Here we declare a destructed variable and set it to the value of useState(). The first object of the variable is the name of collection. The second object of the variable is the function we will eventually use to further update the state of the first object.

**This process of utilizing square brackets is a JavaScript syntax called array destructuring. It allows the declaration of two new variables at the same moment in time. Look at my post here to read more about array and object destructuring. **

We then pass in an empty array to useState() as we plan to update state throughout the component's lifecycle. useState() can take any parameter, such as 'null', '0', 'false', '33'; it does not need to be an object!

This initial code at the top of the component is comparable to using

this.state = {}
Enter fullscreen mode Exit fullscreen mode

and

this.setState({})
Enter fullscreen mode Exit fullscreen mode

in a class component. As we can already tell, our functional component shrinks and dries the code.. by a lot!

useEffect()

This next React hook lets us fetch data and modify the DOM. useEffect(), importantly, houses the function we declared in useState() to maintain and update state as the component lives. Here is an example:

function Categories(props){
    const [categories, setCategories] = useState([])

    useEffect(() => {
        fetch(`http://localhost:3000/categories`)
        .then(response => response.json())
        .then(json => {
            setCategories(json.data)
         })
    }, [])
}

Enter fullscreen mode Exit fullscreen mode

Here's what happens in the code above:

  1. Initial state is set using useState() and stored in "categories" as an empty array.
  2. useEffect() is called which makes a fetch GET request to an API.
  3. The rendered data is passed as json.
  4. setCategories() is invoked and stores the data while updating the state.
  5. The categories collection is now updated and no longer an empty array.

At this moment in the component's lifecycle, a "console.log(categories)" will show something like this:

{
  "bookmarks": [
    "{attributes: {…}, id: \"2\", relationships: {…}, type…}",
    "{attributes: {…}, id: \"1\", relationships: {…}, type…}"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Summary

  • Functional components may now manipulate state because of Hooks.
  • Functional components using Hooks go through the component lifecycle without as much boilerplate code.
  • Functional components using Hooks allows for re-usable behavior.
  • There is not a "better" choice when deciding between Lifecycle Class Methods or Lifecycle Functional Hooks; do what is best for your code.
  • State may always changing; make sure your DOM portrays those changes.

✨ Thank you for reading ✨
✨ Comment below + let's continue the conversation ✨
✨ Ask some questions :) ✨

Top comments (0)