Skip to content Skip to sidebar Skip to footer

How to Call Component Did Mount Again

Introduction

React Hooks are revolutionizing the fashion we develop in React and solving some of our biggest concerns. The useEffect Hook allows us to replace repetitive component lifecycle code.

Essentially, a Hook is a special part that allows yous to "hook into" React features. Hooks are a groovy solution if you've previously written a functional component and realize that yous need to add state to it.

If you're new to Hooks and would like an overview, check out the introduction to React Hooks.

This article assumes that you're familiar with the useState Hook. If you're not, never fear! If you spend a piddling fourth dimension with Convert a React Form-Based Component to a Functional One Using a Country Claw you'll exist on the correct track!

Nigh useEffect

useEffect is short for 'utilize side outcome'. Furnishings are when our application reacts with the outside world, similar working with an API. It allows united states to run a office based on whether something changed. useEffect also allows us to combine componentDidMount and componentDidUpdate.

Nearly Our App

We'll be taking some prewritten class-based code and converting it to a functional component. We'll exist using reactstrap to simplify our formatting and axios to call an external dummy API.

Specifically, we're using jsonplaceholder to pull-in dummy user information on our initial component mount.

Starter Code

Then we are triggering the component to re-render based on a user click and pulling in boosted data nearly the users.

Starter Code, clicked

Getting Started

Only clone over the repo with the starting code:

          $            git            clone https://github.com/alligatorio/utilise-result-hook $            npm            i $            npm            start                  

Have a moment to familiarize yourself with the lawmaking, in particular, the ClassBasedComponent.js file.

You'll notice that we have ii lifecycle methods in this file, componentDidMount and componentDidUpdate.

                      async            componentDidMount            (            )            {            const            response            =            await            axios            .            become            (                          `              https://jsonplaceholder.typicode.com/users              `                        )            ;            this            .            setState            (            {            users            :            response.data            }            )            ;            }            ;            async            componentDidUpdate            (            prevProps            )            {            if            (prevProps.resource            !==            this            .props.resources)            {            const            response            =            await            axios            .            go            (                          `              https://jsonplaceholder.typicode.com/users              `                        )            ;            this            .            setState            (            {            users            :            response.information            }            )            ;            }            }            ;                  

These are both async lifecycle methods that phone call the jsonplaceholder API to bring in a list of users.

In componentDidMount, we say on get-go render, become the user data. Adjacent, on componentDidUpdate we look to see if anything has inverse in props. This tin can be triggered from user initiated events, like in our example, a button printing. In one case the change is detected we say, exit and get the information once again.

We would similar to condense the lifecycle methods into the useEffect Hook and create a function-based component.

Create a Component

Rather than using the same ClassBasedComponent.js file, create a new file called FunctionBasedComponent.js. We're creating a new file so that we tin contrast and compare the 2.

In your terminal, yous tin can run the following to create the new file from your root directory:

          $            touch on            FunctionBasedComponent.js                  

To aid get started, copy and paste the code below into your new file:

                      import            React,            {            useState,            useEffect            }            from            'react'            ;            import            {            Container,            Button,            Row            }            from            'reactstrap'            ;            import            axios            from            'axios'            ;            const            FunctionBasedComponent            =            (            )            =>            {            return            (                                          <                Container                            className                              =                "user-list"                            >                                                                              <h1              >                        My Contacts:                                          </h1              >                                                                              </                Container                            >                        )            }            ;            export            default            FunctionBasedComponent;                  

At present hop over to your App.js file, import your FunctionBasedComponent.js file and replace ClassBasedComponent with FunctionBasedComponent.

Your app should now look something like the screenshot below.

our starting useEffect app


Let'southward start by initializing state with useState.

                      const            [            users,            setUsers            ]            =            useState            (            [            ]            )            ;            const            [            showDetails,            setShowDetails            ]            =            useState            (            false            )            ;                  

To apace recap on useState, to initialize state with the useState hook, we declare both our variable and the function that corresponds to the variable in an array and and then nosotros pass useState() the argument that we'd similar to initialize our variable with.

  • The users state variable is initialized with an empty array and given the function of setUsers.
  • The showDetails state variable is initialized with the value of false and assigned the part of setShowDetails.

Add an API Telephone call

Let'due south go alee and add in our API telephone call as the fetchUsers function.

                      const            fetchUsers            =            async            (            )            =>            {            const            response            =            expect            axios.            get            (                          `              https://jsonplaceholder.typicode.com/users              `                        )            ;            setUsers            (response.data)            ;            }            ;                  

We are essentially pulling this async call from the one-time componentDidMount and componentDidUpdate functions.

Go on in heed nosotros cannot utilize an async role direct inside useEffect. If we ever want to call an async function, we need to ascertain the part outside of useEffect and and then telephone call it within useEffect.

The useEffect Argument

Let'southward talk almost the useEffect hook for a moment. Much like componentDidMount, useEffect will immediately call our function.

                      useEffect            (            (            )            =>            {            }            ,            [            'value'            ]            )            ;                  

By default, useEffect looks to encounter if the array values are different and if they are unlike, the arrow function is automatically chosen.

                      useEffect            (            (            )            =>            {            }            ,            [            'dissimilar value'            ]            )            ;                  

Permit's flip back to our code editor and add together the useEffect hook below our latest part where nosotros will call fetchUsers.

In the code beneath, we're looking at the users object to meet if there are changes.

                      useEffect            (            (            )            =>            {            fetchUsers            (users)            }            ,            [            users            ]            )            ;                  

Common Issues

  • If y'all don't pass an array into the useEffect Hook, your component will continuously reload repeatedly.
                      useEffect            (            (            )            =>            {            fetchUsers            (users)            }            )            ;                  
  • If you pass an empty assortment, we are not watching any variables, and therefore it will but update country on the first return, exactly like componentDidMount.
                      useEffect            (            (            )            =>            {            fetchUsers            (users)            }            ,            [            ]            )            ;                  
  • Every time we create an object in JavaScript, it is a unlike object in retentiveness. Though the code beneath looks the same, the page will be re-rendered because each object is stored in a dissimilar retention address. The same logic applies for arrays.
                      useEffect            (            (            )            =>            {            fetchUsers            (users)            }            ,            [            {            user            :            'Alli Alligator'            }            ]            )            ;                  

Is not equal to!

                      useEffect            (            (            )            =>            {            fetchUsers            (users)            }            ,            [            {            user            :            'Alli Alligator'            }            ]            )            ;                  
  • useEffect office must return a cleanup function or nothing.

To demonstrate triggering another re-return, re-create and paste the code below into your FunctionBasedComponent.js file:

                      import            React,            {            useState,            useEffect            }            from            'react'            ;            import            {            Container,            Push,            Row            }            from            'reactstrap'            ;            import            axios            from            'axios'            ;            const            FunctionBasedComponent            =            (            )            =>            {            const            [            users,            setUsers            ]            =            useState            (            [            ]            )            ;            const            [            showDetails,            setShowDetails            ]            =            useState            (            false            )            ;            const            fetchUsers            =            async            (            )            =>            {            const            response            =            await            axios.            become            (                          `              https://jsonplaceholder.typicode.com/users              `                        )            ;            setUsers            (response.data)            ;            }            ;            useEffect            (            (            )            =>            {            fetchUsers            (users)            }            ,            [            users            ]            )            ;            const            handleClick            =            event            =>            {            setShowDetails            (            !showDetails)            }            ;            return            (                                          <                Container                            >                                                {            users.            map            (            (            user            )            =>            (                                          <ul              cardinal                              =                {                user.id                }                            >                                                                              <li              >                                                                              <strong              >                        {            user.proper name            }                                          </strong              >                                                                              <div              >                                                                              <                Button                            onClick                              =                {                handleClick                }                            >                                                {            showDetails            ?            "Close Additional Info"            :            "More Info"            }                                                                  </                Button                            >                                                {            showDetails            &&                                          <                Container                            className                              =                "additional-info"                            >                                                                              <                Row                            >                                                {                          `              Email:                                            ${                user.email                }                            `                        }                                                                  </                Row                            >                                                                              <                Row                            >                                                {                          `              Phone:                                            ${                user.phone                }                            `                        }                                                                  </                Row                            >                                                                              <                Row                            >                                                {                          `              Website:                                            ${                user.website                }                            `                        }                                                                  </                Row                            >                                                                              </                Container                            >                        }                                                                  </div              >                                                                              </li              >                                                                              </ul              >                        )            )            }                                                                  </                Container                            >                        )            }            export            default            FunctionBasedComponent;                  

Now we have an onClick effect inside a button. On the button click, the state of showDetails is changed, triggering a re-render that will call once more to the API and bring in the boosted details that we need.

Voilà!

                      async            componentDidMount            (            )            {            const            response            =            await            axios.            get            (                          `              https://jsonplaceholder.typicode.com/users              `                        )            this            .            setState            (            {            users            :            response.data            }            )            }            ;            async            componentDidUpdate            (            prevProps            )            {            if            (prevProps.resources            !==            this            .props.resources)            {            const            response            =            await            axios.            get            (                          `              https://jsonplaceholder.typicode.com/users              `                        )            this            .            setState            (            {            users            :            response.information            }            )            }            }            ;                  

Becomes:

                      const            fetchUsers            =            async            (            )            =>            {            const            response            =            expect            axios.            go            (                          `              https://jsonplaceholder.typicode.com/users              `                        )            ;            setUsers            (response.data)            ;            }            ;            useEffect            (            (            )            =>            {            fetchUsers            (users)            }            ,            [            users            ]            )            ;                  

vanceamonly.blogspot.com

Source: https://www.digitalocean.com/community/tutorials/react-replacing-component-lifecycles-with-useeffect

Post a Comment for "How to Call Component Did Mount Again"