How to handle useEffect in React 🚀

2022-11-23

...

useEffect is a hook in React that allows you to perform side effects in functional components. It is a powerful tool that can be used to manage the lifecycle of a component and to handle tasks such as fetching data, setting up subscriptions, and manipulating the DOM.

Benefits

One of the benefits of using useEffect is that it allows you to declutter your code by moving lifecycle methods and related logic out of your component and into a separate function. This can make the developer's code more readable and easier to maintain.

Key Points We Should Pay Attention

useEffect is called after the component has been rendered, and it takes two arguments: a function that contains the side effect logic and an array of dependencies. The function is called every time the component renders unless you specify a list of dependencies in the second argument. If the dependencies have not changed, the function will not be called. This allows you to control when the side effect is executed and can help improve the performance of your application.

It is important to note that useEffect should be used with caution, as it can cause performance issues if not used correctly. For example, if you include a value in the dependencies array that changes frequently, the function associated with useEffect will be called repeatedly, potentially causing performance issues.

By carefully considering the dependencies and the side effects you want to perform, you can use useEffect to improve the performance and maintainability of your application.

Usage

Here is an example of how to use useEffect to fetch data from an API and update the component state with the results:

import { useEffect, useState } from 'react';

function App() {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
      setData(data);
    }
    fetchData();
  }, []);

  return (
    <div>
      {data && <p>{data.message}</p>}
    </div>
  );
}

Set up subscriptions with useEffect, Resize the window

You can also use useEffect to set up subscriptions or perform cleanup tasks when the component is unmounted. For example, you can use useEffect to add an event listener to the window object and clean it up when the component is unmounted:

import { useEffect } from 'react';

function App() {
  useEffect(() => {
    function handleResize() {
      console.log('Window was resized!');
    }
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return (
    <div>
      <p>Resize the window to see the message in the console</p>
    </div>
  );
}

In this example, the function passed to useEffect adds an event listener to the window object. The returned function is used to clean up the event listener when the component is unmounted.

Conclusion

In summary, UseEffect is a powerful tool for managing the lifecycle of a functional component and performing side effects in React. By carefully considering the dependencies and the side effects you want to perform, you can use UseEffect to improve the performance and maintainability of your application.