Misamoto
Misamoto

Reputation: 663

Is there a reason to use useEffect without dependency array?

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.

Upvotes: 11

Views: 3967

Answers (2)

BraisC
BraisC

Reputation: 299

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.

Upvotes: 6

Gayatri Dipali
Gayatri Dipali

Reputation: 1283

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)

Upvotes: 2

Related Questions