13

So, when we use useEffect without a dependancy array, it happens on every render.

But that's what would happen if I just wrote the code directly into the component. So is there a reason to use it?

One thing I can think of is doing something with the cleanup function, but I can't think up a valid usecase.

3
  • 5
    But that's what would happen if I just wrote the code directly into the component is not correct. useEffect functions run AFTER a render, not DURING. Commented Nov 15, 2020 at 0:48
  • 1
    A valid use is to use setTimeout and then run clearTimeout in the cleanup function (which takes effect when the component unmounts). The official React docs show another example: reactjs.org/docs/hooks-effect.html#effects-with-cleanup Commented Nov 15, 2020 at 1:07
  • Does this answer your question? Why would we use useEffect without a dependency array? Commented May 16, 2021 at 9:43

2 Answers 2

7

But that's what would happen if I just wrote the code directly into the component.

Actually, that is not entirely true.

For example if you update a useState to the same value, React will reevaluate the function component but will not trigger effects, it will cause the code outside useEffect to execute, but not the one inside useEffect.

This is said in the official docs, Bailing out of a state update

And this is an example of the matter.

Sign up to request clarification or add additional context in comments.

Comments

2

The thing is both a i.e, a normal JS-function and a useEffect without any dependency does the same work but the difference is that :

  1. useEffect is only accessible in a React code not normal JS. It has more power in terms of react. Hence, Hooks scope is limited to the React code world.
  2. In the class-based components, the Hooks won't work but regular functions will.
  3. React will remember the function you passed (we'll refer to it as our “effect”), and call it later after performing the DOM updates but the same might not be true in other cases.(Important)
  4. By default, effects run after every completed render, but you can choose to fire them only when certain values have changed but this is not something that's easy with normal JS-functions (Just an side advantage apart from the question)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.