Home > Software engineering >  why useEffect is called infinitely
why useEffect is called infinitely

Time:04-28

In useEffect in my react component I get data and I update a state, but I don't know why the useEffect is always executed:

const Comp1 = () => {
    const [studies, setStudies]= useState([]);
    React.useEffect( async()=>{
          await axios.get('/api/expert/',
         )
        .then((response) => {
          setStudies(response.data.studies);     
    
        },  (error) => {
          console.log(error );
        })
          console.log("called  "  studies);
    
    },[studies]);
    return(
         <Comp2 studies={studies}/>
          )

}

Here is my second Component used in the first component...

 const Comp2 = (props) => {
        const [studies, setStudies]= useState([]);
        React.useEffect( ()=>{

              setStudies(props.studies)
        
        },[props.studies, studies]);


        return(
             studies.map((study)=>{console.log(study)})
    
    }

CodePudding user response:

EDIT

const Comp2 = (props) => {

  // for some brief time props.studies will be an empty array, []
  // you need to decide what to do while props.studies is empty.

  // you can show some loading message, show some loading status,
  // show an empty list, do whatever you want to indicate
  // progress, dont anxious out your users
  return (
    props.studies.map((study)=>{console.log(study)}
  )
}

You useEffect hook depends on the updates that the state studies receive. Inside this useEffect hook you update studies. Can you see that the useEffect triggers itself?

A updates B. A runs whenever B is updated. (goes on forever)

How I'd do it?

const Comp1 = () => {
  const [studies, setStudies]= useState([]);
  React.useEffect(() => {
    const asyncCall = async () => {
      await axios.get('/api/expert/',
      )
      .then((response) => {
        setStudies(response.data.studies);     
      }, (error) => {
        console.log(error );
      })
      
      console.log("called  "  studies);
    }
      
    asyncCall();
  }, []);

  return(
    <Comp2 studies={studies}/>
  )
}

CodePudding user response:

useEffect() has dependency array which causes it to execute if any value within it updates. Here, setStudies updates studies which is provided as dependency array and causes it to run again and so on. To prevent this, remove studies from the dependency array. Refer: How the useEffect Hook Works (with Examples)

  • Related