useEffect besides useState is the most important React hook you have, so you need to understand it. Therefore, I again, want to make it clear at which point of time, which part of useEffect kicks in and executes. Next, I'll present some useEffect use cases. First example is for the case of a useEffect that runs when a state is updated or a key is pressed.
ReadSometimes you have an useEffect that needs to do some cleanup work and that sounds very abstract so let me give you a more concrete example. Let's say that we execute a function in a useEffect hook that essentially is executed on every keystroke, like in the following example:
ReadYou learned, that you should add "everything" you use in the effect function as a dependency - i.e. all state variables and functions you use in there.
ReadWe need dependencies in a useEffect hook when we want to execute the code from the useEffect after every dependencies change. So if we want that our code from useEffect to run when the component is loaded we will put for dependencies an empty array and if we want to run after a certain depency change we need to add that dependency in the array. If we delete the array we will have an infinite loop. useEffect in general is a super helping hook that helps you deal with code that should be executed in response to something and something could be the component being loaded, it could be the email address being updated, it could be anything, whenever you have an action that should be executed in response to some other action, that is a side effect and that is where a useEffect is able to help you.
Read