Reputation: 663
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
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
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 :
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.Upvotes: 2