DEV Community

Violeta
Violeta

Posted on

useEffect Hook

Hooks give us the ability to use the state and other React features writing a functional component instead a class based component.

One of the most used hooks is useEffect, this hook allow us to use something like lifecycle methods but in a functional component.

The first argument of useEffect is always a function and the second argument is an array of dependencies, this argument allows to take control of when we want to execute the function.

If you want to use useEffect hook you need to import:

import { useEffect } from 'react';
Enter fullscreen mode Exit fullscreen mode

useEffect has 3 ways to use it:

When a component is rendered only the first time

  //Run at initial render 
  useEffect(() =>{
    console.log("Run at initial render ");   
  }, []); 
Enter fullscreen mode Exit fullscreen mode

You have to pass an empty array and code inside the function only will be executed one time, only when component is rendered

When a component is rendered the first time and every time dependencies in array had changed

  //Run at initial render and every render if total has changed 
  useEffect(() =>{
    console.log("Total has changed to: "+total); 
  }, [total]); 
Enter fullscreen mode Exit fullscreen mode

You can pass an array with the variables you want, you can pass one or more values and the function will be executed every time one variable changes.

When a component is rendered the first time and every time it rerenders

useEffect(() =>{    
    console.log("First time and after every render "); 
  });
Enter fullscreen mode Exit fullscreen mode

With this method you don't pass an array.

Be careful with the array dependencies because you could fall into an infinite loop or have performance issues, especially when no dependencies are declared.

Alt Text

You can see an easy example here

Top comments (0)