DEV Community

SavvyShivam
SavvyShivam

Posted on

useEffect in React

Applications in the real world rarely work in isolation. Side-effects are the norm in making web apps. For example, element.addEventListner is triggered as a side effect or sending API requests.

There are three parts to this hook.

Effect

The effect is the code you want to execute when something changes in the dependency array.

Cleanup

This code is run just before the component unmount to do clean up stuff, like removing event listeners, canceling API requests, etc.

Dependencies

This is an array of variables (props or state) that are observed by the hook. The effect only executes if one or more of the dependencies change.

  • No Dependency array means the effect will execute on every rerender of the component i.e. whenever any of the props or state changes.

  • Empty Dependency Array [] means the effect only runs on the first render of a component

Here is a more complete example of how useEffect works

useEffect takes two arguments. However, the second argument is not compulsory

  1. Function

  2. Dependency

The first argument is the function that will get executed every time the useEffect hook is called i.e. every time it re-renders.
The second argument i.e. the dependency will make sure that the function executes only when a specific value of the program changes.
This will be an array called the dependency array and it will contain the values which when changes will trigger the execution of the Hook.

Lets us write some code to understand :

The very first code that we have to write to use the useEffect Hook is the import code.

To add side effects to your react component, the useEffect hook is used. The syntax of the hook is as follows

Let us now create and understand the above concepts.

The useEffect in the above code has taken one argument : the function setTimeout. This function takes yet another function that is named as setCount and the function increments the current time by 5. The 1000 in here refers to the time limit in which the function should be re-executed.

When we execute this piece of code we find out that the time keeps on incrementing by 5 and does not stop.
Now to increment the time by 5 according to our desired way, we add the dependency into the useEffect Hook
To increment the timer only once, we do add the following :

By adding an empty square bracket, the function will only get executed on the first render. Thus the timer will not keep on incrementing for infinite time.

The code of the above program is given below:
https://codesandbox.io/s/use-effect-5x7uxq

Here is another example with a real world application

Top comments (0)