0

Inside a React Project. Let's say you start at the FavoriteList-page, from there you go to the ItemInfo-page. My question is, when you go back to the Favorites-page, is the useEffect(() => {}, []) hook (similar to the ComponentDidMount) load again? Because it's not loading for me :'( It only loads the very first time.

Dominik
  • 6,078
  • 8
  • 37
  • 61
Alfredo C.
  • 56
  • 2
  • Share your code so we can help you. – Dominik Apr 22 '21 at 21:41
  • What exactly do you mean by "you go to the ItemInfo-page", are you using react-router? However, it appears that your component isn't unmounting. Try running the following code: `useEffect(() => { return () => console.log("unmounted") }, [])` and check if it triggers the unmount. – Hansel Apr 22 '21 at 21:42
  • Hi guys thank you very much! My problem was that I wasn't correctly updating my component state. – Alfredo C. Apr 30 '21 at 21:49
  • 1
    @MustKillBill, that log inside the useEffect was helpful. – Alfredo C. Apr 30 '21 at 21:49

1 Answers1

0

Use effect always runs on the first render of a component, then after that depends on what you pass as your second argument.

If you want useEffect to run ONLY on the first render of the component, use this:

useEffect(() => {}, [])

If you want useEffect to run on EVERY render, use this (no second argument):

useEffect(() => {})

If you want useEffect to run on the first render of the component, AND on state(s) changes, use this:

useEffect(() => {}, [state, anotherState])

If you are trying to avoid useEffect rendering on the first render, you need to use a UseRef hook. This post will tell you how to go about doing this.

Noah Gwynn
  • 256
  • 2
  • 12