2

Is there any difference with these 3 useEffects

useEffect(() => {
    return console.log('useEffect with undefined dep');
});

useEffect(() => {
    return console.log('useEffect with empty array dep');
}, []);

useEffect(() => {
    return console.log('useEffect with filled dep');
}, [filledDep]);
  • 2
    yes there is, everything is explained in the official tutorial – Konrad Oct 18 '22 at 12:39
  • Does this answer your question? [In useEffect, what's the difference between providing no dependency array and an empty one?](https://stackoverflow.com/questions/58579426/in-useeffect-whats-the-difference-between-providing-no-dependency-array-and-an) – samuei Oct 18 '22 at 13:09

3 Answers3

1

As React docs says:

  • when an empty array [] is supplied

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.

  • When there is no second argument, it works as both componentDidMount and componentDidUpdate:

    // Similar to componentDidMount and componentDidUpdate:
    useEffect(() => {
        // Update the document title using the browser API
        document.title = `You clicked ${count} times`;
    });
    
  • and if you supply arguments, then it will re-run the effect when arguments were changed and it will also still run after the initial render

    useEffect(() => {
        document.title = `You clicked ${count} times`;
    }, [count]); // Only re-run the effect if count changes
    
StepUp
  • 36,391
  • 15
  • 88
  • 148
0

To clean up after a component unmounts, we have a simple way to perform the equivalent of the componentWillUnmount using the useEffect Hook.

The only thing that we need to do is to return a function inside the callback function of the useEffect Hook.

if a component renders multiple times (as they typically do), the previous effect is cleaned up before executing the next effect.

Mohamad Ahmadi
  • 248
  • 2
  • 7
0

Yes there are...

  1. It will run on every-time when component renders/re-renders
  2. It will run only once when the component first renders
  3. It will run when component first renders and every-time when its dependency filledDep changes.
ShoaibAh
  • 167
  • 4