React: useEffect & dependencies
We 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.
In the next example you can see a useEffect hook without dependencies, because it is used to load the data from local storage when the component is loaded and to set the loggin state to true if the login data is saved in the local storage.
In the next example you can see a login component, where we use the useEffect hook with some dependencies, enteredEmail and enteredPassword. We run the useEffect every time when the enteredEmail and enteredPassword values are changed because we need to set the value for formIsValid state:
Category: React Tags: #react, #javascript