If you do not pass an empty array as an argument to useEffect,
the effect will run on every render of the component.
This means that any code ins...
For further actions, you may consider blocking this person and/or reporting abuse
Bonus points if you also add a cleanup to your useEffect, to cancel the request when the component gets unmounted during fetching. In your current code the state update will produce an error if the component gets unmounted during fetching (cant update state of unmounted component).
Thank you, that's a great addition
what do you think about this dev.to/csituma/do-i-need-to-use-cl...
I mostly agree with that, except that you should also cleanup if you do delayed state updates in your useEffect, to avoid updating state on unmounted components (which will result in an error).
Providing no dependency in the useEffect give sideEffects and introduce bugs. Always, Always give the dependencies required by useEffect. By using empty array you can get your desired result but it will definitely introduce bug and hard to maintain the code in long run.
This is correct.
However in instances where there are no dependencies, an empty array is okay,
Don't you agree?
Could you give an example where the instance does not have any dependency? Even if you use a variable/function, you have to give a dependency.
Hmm...
A simple fetch?
useEffect(() => {
fetch("pokeapi.co/api/v2/type/3")
}, []);
In this example, the
useEffectwill ask for the dependency offetchfunction.The corrected code:
If you use the empty array as a dependency and if you have any linter, you will surely get an error/warning based on the setup.
In your example, using fetch as dependency is unnecessary and will infact bring up a warning(mutating it can't cause a re-render because it will be recognised as an Outer scope value )
You should try run the code