Difference between useEffect, useMemo and useCallback in React

React is a well-known library for building UIs with JavaScript. It gives a few snares, which are capabilities that let you use states and different elements in practical parts. The most well-known snares are useState and use effect, which permit you to oversee state and secondary effects in your details.

In any case, React additionally offers a few different snares that can assist you with optimizing the exhibition of your parts and keep away from pointless re-rendering. These snares are use callback, useMemo and useEffect. In this article, we will explain what these snares do, how they contrast, and when to utilize them.

What is useCallback?

useCallback is a snare that profits a memoized form of a callback capability. This implies that the capability might be made once and reused on ensuing renders, except if one of its conditions changes. This can forestall pointless re-rendering of kid parts that rely upon the callback capability as a prop.

For instance, assume we have a part that delivers a list of things and permits the client to flip the visibility of everything. We can utilize useState to store the visibility condition of everything, and useCallback to make a capability that flips the visibility of a given thing.

import React, { estate, useCallback } from “react”;

function List({ items }) {

  // Create an array of booleans to store the visibility state of each item

  const [visible, setVisible] = useState(items.map(() => true));

  // Create a memoized function that toggles the visibility of an item at a given index

  const toggleVisibility = useCallback(

    (index) => {

      // Copy the visible array and update the value at the index

      const newVisible = […visible];

      newVisible[index] = !newVisible[index];

      // Set the new visible array as the state

      setVisible(newVisible);

    },

    [visible] // The function depends on the visible state

  );

  return (

    <ul>

      {items.map((item, index) => (

        // Pass the item, the visibility state, and the toggle function as props to a child component

        <ListItem

          key={item.id}

          item={item}

          visible={visible[index]}

          toggleVisibility={() => toggleVisibility(index)}

        />

      ))}

    </ul>

  );

}

In this example, we use useCallback to make a toggleVisibility capability that relies upon the visible state. This way, we guarantee that the capability might be reproduced when the visible state changes, and not on each render of the List part. This can forestall pointless re-rendering of the ListItem parts that get the toggleVisibility capability as a prop.

What is useMemo?

useMemo is a snare that profits a memoized esteem that is the consequence of a capability. This implies that the capability might be executed once and its outcome will be reserved for resulting renders, except if one of its conditions changes. This can keep away from costly estimations on each render when the outcome is not going to change.

For example, assume we have a part that delivers a few statistics in light of an enormous informational index. We can utilize useMemo to make a capability that computes the statistics and returns them as an item.

import React, { useMemo } from “react”;

function Statistics({ data }) {

  // Create a memoized function that calculates some statistics from the data

  const stats = useMemo(() => {

    // Assume data is an array of numbers

    // Calculate the sum, average, min, and max of the data

    const sum = data.reduce((a, b) => a + b, 0);

    const average = sum / data.length;

    const min = Math.min(…data);

    const max = Math.max(…data);

    // Return an object with the statistics

    return { sum, average, min, max };

  }, [data]); // The function depends on the data prop

  return (

    <div>

      <p>Sum: {stats.sum}</p>

      <p>Average: {stats.average}</p>

      <p>Min: {stats.min}</p>

      <p>Max: {stats.max}</p>

    </div>

  );

}

In this example, we use useMemo to make a details object that relies upon the information prop. This way, we guarantee that the capability that works out the statistics may be executed when the information prop changes, and not on each render of the Statistics part. This can stay away from costly estimations on each render when the information is not going to change.

What is useEffect?

useEffect is a snare that allows you to perform secondary effects in your parts. Incidental effects are anything that influences something beyond your part, like fetching information, manipulating the DOM, setting clocks, logging, and so on. useEffect acknowledges a capability that contains the secondary effect code, and a discretionary cluster of conditions that determine when the impact ought to run.

For example, assume we have a part that brings a few information from a Programming interface and renders it on the screen. We can use useEffect to make a capability that brings the information and updates the state when the part mounts or when the query prop changes.

import React, { useState, useEffect } from “react”;

function Data({ query }) {

  // Create a state to store the data

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

  // Create a function that fetches the data from an API

  const fetchData = async () => {

    // Assume query is a valid URL

    // Fetch the data from the query

    const response = await fetch(query);

    const data = await response.json();

    // Update the state with the data

    setData(data);

  };

  // Use useEffect to run the function when the component mounts or when the query prop changes

  useEffect(() => {

    fetchData();

  }, [query]); // The effect depends on the query prop

  return (

    <div>

      {data ? (

        // Render the data

        <pre>{JSON.stringify(data, null, 2)}</pre>

      ) : (

        // Render a loading message

        <p>Loading…</p>

      )}

    </div>

  );

}

In this example, we use useEffect to make a fetchData capability that relies upon the query prop. This way, we guarantee that the capability might be executed when the part mounts or when the query prop changes, and not on each render of the Information part. This can stay away from pointless fetching of information and updating of state.

How are useCallback, useMemo and useEffect different?

useCallback, useMemo and useEffect are snares that can assist you with optimizing the presentation of your parts and stay away from pointless re-rendering. However, they have different purposes and use cases.

•useCallback is used to make a memoized callback capability that will possibly change when its conditions change. This can forestall pointless re-rendering of youngster parts that rely upon the callback capability as a prop.

•useMemo is used to make a memoized esteem that is the consequence of a capability that will possibly change when its conditions change. This can stay away from costly computations on each render when the outcome is not going to change.

•useEffect is used to perform secondary effects in your parts that will possibly run when their conditions change. This can keep away from pointless incidental effects and state reports on each render.

When to use useCallback, useMemo and useEffect?

UseCallback, useMemo and useEffect are useful snares that can assist you with optimizing the presentation of your parts and stay away from pointless re-rendering. However, they ought not be used indiscriminately or without understanding their suggestions. Here are a few overall principles on when to use them:

•Use useCallback when you have a callback capability that is passed as a prop to a kid part and you need to forestall pointless re-rendering of the kid part. Ensure you determine every one of the conditions of the callback capability in the reliance cluster.

•Use useMemo when you have a worth that is gotten from a costly calculation and you need to try not to recalculate it on each render. Ensure you determine every one of the conditions of the calculation in the reliance exhibit.

•Use useEffect when you have a secondary effect that should be performed subsequent to rendering or when a few conditions change. Ensure you determine every one of the conditions of the aftereffect in the reliance cluster. Likewise, ensure you tidy up any assets made by the secondary effect in a return capability if necessary.

Conclusion

In this article, we have explained what useCallback, useMemo and useEffect are, how they contrast from one another, and when to use them. We have likewise shown a few examples of how to use these snares in React parts. We trust this article has assisted you with understanding these snares better and how to use them actually in your React projects.

In the event that you have any inquiries or criticism, kindly go ahead and leave a remark beneath. Much obliged to you for reading! 😊

Leave a Comment