skip to Main Content

I am just now Learning React JS, stuck with the following issue
useEffect is called Multiple Times, even when state value is passed in Dependencies. How to fix it?

import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom';

const ViewProfileUseEffect = () => {
    const [userList, setUserList] = useState([]);
    const naviagte = useNavigate();
    useEffect(() => {
        axios.get("http://localhost:4000/users").then((response) => {
            setUserList(response.data);
            console.log('I am inside useEffect');
        }).catch((error) => {
            alert("Something went wrong")
        })
    }, [userList]);
function handleProfile(id) {
        naviagte(`/profile/${id}`);
    }

    function deleteProfile(id) {
        axios.delete(`http://localhost:4000/users/${id}`).then((response) => {
            console.log(`Delete Response Data ${response.data}`);
        }).catch((error) => {
            alert("Something went Wrong");
        })
    }
    return (
        <>
            <h3>View Profile</h3>
            <div className='container' style={{ backgroundColor: 'bisque', width: '500px', padding: '20px', borderRadius: '5px' }}>
                <table className='table'>
                    <thead>
                        <tr>
                            <th scope='col'>UserName</th>
                            <th scope='col'>Email ID</th>
                            <th scope='col'>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        {userList.map((user) => {
                            return (
                                <tr key={user.id}>
                                    <td>{user.userName}</td>
                                    <td>{user.userEmail}</td>
                                    <td>
                                        <button className="btn btn-warning" onClick={() => handleProfile(user.id)}>View Profile</button>
                                        <button className="btn btn-danger" onClick={() => deleteProfile(user.id)}>Delete Profile</button>
                                    </td>
                                </tr>
                            )
                        })}
                    </tbody>
                </table>
            </div>
        </>
    )
}

export default ViewProfileUseEffect

The Output I got

enter image description here

"I am inside useEffect" is coming in console multiple times endlessly

How to stop it?

3

Answers


  1. useEffect(() => {
        axios.get("http://localhost:4000/users").then((response) => {
            setUserList(response.data);
            console.log('I am inside useEffect');
        }).catch((error) => {
            alert("Something went wrong")
        })
    }, [userList]);
    

    when you fetch the data the userList is change and that makes useEffect rerun and also when it rerun the userList is also change or effected so it will be also rerun and so on … leave the array empty,
    or disable reactStrict mode from the main react file where you call the root div.

    Login or Signup to reply.
  2. Please be informed that when you’re in the development environment, and your <App /> component is rendered inside a <React.StrictMode><App /><React.StrictMode>, your useEffect hook is going to run twice when you component mounts. However, this doesn’t happen in the production environment. If you don’t want your useEffect hook to run twice in development environment, you can remove the React.StrictMode wrapper around the <App/ > component render.

    In addition, you have userList state in your useEffect dependency but the state variable has no effect on your api call. You should remove it from your dependency list otherwise, you would run into infinite loop.

    I believe the above instructions should fix your issues.

    Login or Signup to reply.
  3. you should not include usersList as dependency for your useEffect!
    and it has a good reason.
    when the component finishes rendering (the mounting phase) it will run the useEffect. so it will fetch the data and set the users.
    but the usersArray has changed again and it will run the useEffect again and again..
    you should remove the dependency and it will be fixed.

     useEffect(() => {
        axios.get("http://localhost:4000/users").then((response) => {
            setUserList(response.data);
            console.log('I am inside useEffect');
        }).catch((error) => {
            alert("Something went wrong")
        })
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search