1

I have this code that makes my app hang and Expo using 300% CPU. It looks like an infinite loop but it does not crash and I can't figure out why it's an infinite loop or why its not crashing.

I scraped out the useless parts:

ContainerComponent.js

const [cardsReady, setCardsReady] = useState(0)

const cardLoaded = () => {
    setCardsReady(cardsReady + 1)
}

return keys.map((component) => {
<Card key={'some key} 
    articles={'somearticle'} color={'#eeeeee'} 
    onLoaded={cardLoaded}
    category={'some category}
/>
})

Card.js

useEffect(() => {
onLoaded()

})
2
  • How are you testing and debugging this code? stackoverflow.com/questions/905322/… Look for a "slow script performance" warning and try to kill it. Then, read Drew's comment. Jan 12, 2021 at 6:25
  • 2
    onLoaded updates the state in the parent component which will rerender the parent which will rerender Card, this will cause a render loop since there is no dependency on the useEffect hook; it will call its callback every render. Sounds like it should load only once, use an empty dependency ([]) array to run the effect only once when the component mounts.
    – Drew Reese
    Jan 12, 2021 at 6:27

2 Answers 2

0

please use a dependencies array to only execute useEffect hook once.

Card.js

useEffect(() => {
onLoaded()

},[]);

In the dependencies array you can leave it empty for execute it once as i said or put dependencies variables, that is, specify the variables when it value changes will execute code inside useEffect.

7
  • I tried both, I put a console log inside cardLoaded and it's not even firing, just really high CPU
    – Neuie
    Jan 12, 2021 at 6:43
  • And? The loop stills there?
    – b3lg1c4
    Jan 12, 2021 at 6:44
  • Nothing happens as soon as I trigger the .map to render the Card components it stops doing anything and eats CPU
    – Neuie
    Jan 12, 2021 at 6:46
  • How many Cards are you rendering? May you can use react-virtualized
    – b3lg1c4
    Jan 12, 2021 at 6:48
  • 19, I will take a look at react-virtualized
    – Neuie
    Jan 12, 2021 at 6:50
0

The issue here with your code is with every state update in functional component it is re-rendered. To avoid that issue you need to add dependency array to useEffect, and we are checking the if the component has mounted or not

Card.js

const Card = (props) => {
  useEffect(() => {
    let mounted = true;
    if(mounted && props.onLoaded){
      props.onLoaded();
    }
    return () => mounted=false;
    //eslint-disable-next-line
  },[]);
  return <div></div>;
};

I have created a local state to check whether the component is loaded or not. I know the answer is a bit complicated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.