DEV Community

Tyeb
Tyeb

Posted on

useEffect()

useEffect is a hook that manages side-effects in functional components.

Image description


A function will always produce the same output when given the same input; these functions are known as Pure functions. This function produces a predictable output.

Image description

Side-effects are the actions performed to communicate with the outside world. These actions are unpredictable.

Example of Side-effects

  • Making an API request.

  • interacting with DOM.

  • using localStorage or setTimeout or setInterval functions.

Image description


useEffect hook will take two arguments a callback function which will be called after a component render and a dependency array.this array tells react when to call this function.

If no array is passed, useEffect will run at every render.

function MyComponent(){
 useEffect(()=>{
  console.log("Hello World");
 });
}

Enter fullscreen mode Exit fullscreen mode

If an Empty array is passed, useEffect will run only at initial render.

function MyComponent(){
 useEffect(()=>{
  console.log("Hello World");
 },[]);
}
Enter fullscreen mode Exit fullscreen mode

If array with a value inside is passed, useEffect will run whenever that value is changed between renders.

function MyComponent(){
 const [value,setValue]=useState(0);
 useEffect(()=>{
  console.log("Hello World");
 },[value]);
}
Enter fullscreen mode Exit fullscreen mode

Comparing Class-based components with Functional-based components.

we should avoid code duplication in componentDidMount and componentDidUpdate. So here we introduce useEffect hook in functional component.


Cleanup function in useEffect

Image description

lets say we are using a setInterval function that runs every second and this side-effect is not cleaned up. So whenever our component is unmounted or you moved to the next page this setInterval will still be running in background. This is bad and is known as memory leak.

Image description


componentDidMount()

useEffect(()=>{
 console.log("component mount");
 },[])
Enter fullscreen mode Exit fullscreen mode

componentDidUpdate()

useEffect(()=>{
 console.log("component update");
 },[values])

Enter fullscreen mode Exit fullscreen mode

componentWillUnmount()

useEffect(()=>{
 return ()=>console.log("component removed");
 },[])
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)