What Is The Difference Between useEffect And useMemo With Examples

The useEffect and useMemo hooks are two functions that are used to manage state and performance in a React application.

The useEffect hook is used to perform side effects in a React component. This can include things like making a network request, setting up a subscription, or updating the DOM in response to a change in state. Here is an example of how the useEffect hook could be used to make a network request in a React component:

import { useEffect, useState } from 'react';

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

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

  return (
    <div>
      {data ? <p>{data.message}</p> : <p>Loading...</p>}
    </div>
  );
}

In this example, the useEffect hook is used to make a network request to retrieve some data from an API. The useEffect hook takes a function as an argument, which is executed after the component renders. The function contains the code to make the network request and update the component's state with the response data. The empty array at the end of the useEffect hook tells React to only execute the side effect when the component mounts, rather than on every render.

The useMemo hook is used to optimize the performance of a React component by memoizing (caching) the results of a calculation or function. This can be useful in cases where the calculation or function is expensive, and the result is not likely to change often. Here is an example of how the useMemo hook could be used to optimize the performance of a component that calculates the sum of an array of numbers:

import { useMemo } from 'react';

function ExampleComponent({ numbers }) {
  const sum = useMemo(() => {
    let total = 0;
    for (const number of numbers) {
      total += number;
    }
    return total;
  }, [numbers]);

  return (
    <div>
      <p>The sum of the numbers is {sum}</p>
    </div>
  );
}

In this example, the useMemo hook is used to calculate the sum of the numbers in the numbers array. The useMemo hook takes a function as an argument, which is executed and the result is cached. If the numbers array does not change, the cached result is returned, rather than re-executing the function. This can help to improve the performance of the component by reducing the number of unnecessary calculations.

In summary, the useEffect hook is used to perform side effects in a React component, while the useMemo hook is used to optimize the performance of a component by memoizing the results of a calculation or function.