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.
So what happens when the dependency array is empty? It simply means that the hook will only trigger once when the component is first rendered. So for example, for useEffect it means the callback will run once at the beginning of the lifecycle of the component and never again.
When I was just starting with react, the issue I faced was, useEffect hook of react got called every time state or props got changed. In the above snippet, there is no dependency array so this will be called every time if state or props changes.
The motivation behind the introduction of useEffect Hook is to eliminate the side-effects of using class-based components. For example, tasks like updating the DOM, fetching data from API end-points, setting up subscriptions or timers, etc can be lead to unwarranted side-effects.
Always use useEffect for asynchronous tasks Instead of writing asynchronous code without useEffect that might block the UI, utilizing useEffect is a known pattern in the React community — especially the way the React team has designed it to execute side effects.
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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With