Problem with infinite loop component in React

Asked

Viewed 501 times

1

I have my header component, where I search the user information through the api, the problem is that this search gets stuck in a loop that keeps searching the user non-stop.

code::

 import React, { useState, useMemo } from "react";
import axios from "axios";
import Logout from '../Logout/';
import "./style.css";

const user_id = localStorage.getItem('user_id');
const avatar = localStorage.getItem('avatar');

export default function Header(){

    const [user, setUSer] = useState(null);

    useMemo(async () => {
        const data = await axios.get(`http://localhost:3001/api/users/${user_id}`);
        setUSer(data.data)
        console.log(data);
    })




    console.log(user)


    if(user !== null){
        return (
            <header className="async-header">
                <div className="user-content">
                    <span className="user-name">
                    {user.username}
                    <span>{user.email}</span>
                    <a href="/#" className="btn-logout" onClick={Logout}>Deslogar</a>
                    </span>
                <div className="user-image" style={user.avatar ? {backgroundImage: `url(${user.avatar})`} : null}></div>

                </div>


            </header>
        )
    }else{
        return <div />
    }
}

1 answer

2


The method useMemo receives two parameters, the first one (you sent) is a function in which the return will be the value that useMemo will store and return to its variable. The second parameter is an array of dependencies where the stored value will be recalculated only if one of these dependencies has been modified.

To fix the problem you have, add the second parameter in useMemo should already be enough.

const user = useMemo(async () => { ... }, [ user_id ])

Only one detail about useMemo and useEffect + useState.

When using useMemo React first performs the operation within useMemo and then renders its component. When you use the useState + useEffect React first renders its component with the default value, then executes the useEffect that updates its state that generates a Trigger to render its component again (this time with the value updated by useEffect).

In your case, you are sending a request to a localhost server so the response time is almost instantaneous however, if this request takes any time for any reason (network latency or very time-consuming operation) your page will be blank for the user.

  • 1

    Thank you for the answer and the explanation. I had tested an example, just like this one and it hadn’t worked, a few hours later I found out that React for some reason hadn’t updated the code and was rendering the site using a slightly worse example than I put on it. More after restarting the server started working again.

  • Your explanation helped me create a cleaner code.

  • 1

    No problem, happy to help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.