DEV Community

Cover image for Understanding of React Hooks - useEffect.
Vidit Kushwaha
Vidit Kushwaha

Posted on • Edited on

Understanding of React Hooks - useEffect.

What is useEffect hook?

According to the creator of react, Jordan Walke, it is introduced as way to manage side effects to functional React components. What are the side effects in functional react component? It mainly refers to the any changes that effect the program state, like modifying a variable, printing to the console, or making an API call, changing the DOM are few that considered side effects. In functional programing, minimizing side effects is important for writing predictable and maintainable code.

Syntax

useEffect is usually called at top level of your component. And required function to executed is passes as argument to useEffect, so every time component is re-render the useEffect is called.

Second argument is passed as array of dependencies. This array tells React to re-run the effect (the first argument function) whenever any of the values in this array change. In this case, the effect behaves like a combination of componentDidMount and componentDidUpdate from class components.

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

The array of dependencies is empty then in that case the effect will only run once after the initial render of the component. else its re-runs whenever any of the values in the dependencies array change.

// Component.tsx

import { useEffect } from 'react';

export default function Component() { 

useEffect(() => {
  fetch('/api/data')
    .then(response => response.json())
    .then(data => setData(data));
}, []);
//...
}
Enter fullscreen mode Exit fullscreen mode

useEffect with CleanUp

As we know that useEffect hook in React allows you to perform side effects in your functional components. It can also return a cleanup function that runs when the component unmounts, as well as before re-running the effect due to changes in dependencies.

import React, { useEffect } from 'react';

function Component() {
  useEffect(() => {
    // This is the effect
    console.log('Component mounted');

    // This is the cleanup function
    return () => {
      console.log('Component unmounted');
    };
  }, []); // Empty dependencies array means the effect runs only once

  return <div>Hey, Lary</div>;
}

export default Component;
Enter fullscreen mode Exit fullscreen mode

In this example, the console.log('Component mounted') line runs once when the component mounts. The cleanup function () => console.log('Component unmounted') runs when the component unmounts.

This is useful for handling any necessary cleanup for your effects, such as cancelling API requests, or removing event listeners.

Why is Cleanups required?

useEffect(() => {
  const timer = setInterval(() => {
    setTime(prevTime => prevTime - 1);
  }, 1000);

  return () => {
    clearInterval(timer);
  };
}, []);
Enter fullscreen mode Exit fullscreen mode

Cleanup is necessary in React to avoid memory leaks and unwanted behavior. When you use the useEffect hook to set up something, like an event listener or a timer, that setup is often persistent and won't automatically go away when the component unmounts. it's not tied to the lifecycle of the component. for example, if you start a timer with setInterval, the timer will continue to run and call its callback function at the specified interval, even if the component that started it has unmounted. The browser doesn't know that the component has unmounted and that it should stop the timer.

That concludes the fundamentals of useEffect. If you enjoyed the article, please share it with your friends and the community. I will put out content a further article about useContext soon.

For additional articles, you can visit the blog.viditkushwaha.

Top comments (0)