Heim > Web-Frontend > js-Tutorial > Hauptteil

„useMemo' und „useCallback' verstehen: Eine umfassende Anleitung

PHPz
Freigeben: 2024-08-28 06:11:06
Original
209 Leute haben es durchsucht

Understanding `useMemo` and `useCallback`: A Comprehensive Guide

useMemo and useCallback are two powerfull React hooks that play a crucial role in prevent un-necessary re-renders which result in optimizing component performance. They are essential tools for developers to create responsive and efficient React application.

In this guide will dive into explaining useMemo and useCallback what are their similarities and how they differ from each other. We will understand how to implement them, When to use each one.

why should you use useMemo or useCallback

Usually in React most calculation are fast, But sometimes you have a calculation on very large array, or some expensive computation that don't need to execute on every re-render.

useMemo and useCallback hooks can help solve this issue by caching those expensive computation between re-renders.

what is useMemo and how to use it.

useMemo is React hook that caches the result of a calculation between re-renders and it takes two arguments:

  • CalculatedValue: The function calculating the value you want to cache. The function should not accept any parameters and it should be pure, and return any type of value. React will return the same calculated result if the dependencies has not changed, Otherwise it will calculate a new result and cache it.
  • dependencies: the list of all reactive values references that are inside your CalculatedValue, from states variables constants and function calls. React will try to compare each reactive value with it's previous value using Object.it comparison.

useMemo usage

To cache a calculation between re-renders wrap it a useMemo hook at the top level of the component.

useMemo(fn, dependencies)

const App = () => {
  const useMemo(() => {
    filterTodo(todos, tab)
  }, [todos, tab])
  return(...)
}

export default App
Nach dem Login kopieren

Notice that the first parameter of useMemo is a function with no parameters.

The first time React will calculate the result value of first parameter of useMemo, Then memoize the second parameter which is the list of dependencies. React will cache the calculated result between re-renders and only re-calculate the result when one of the dependencies values changes.

what is useCallback and how to use it.

useCallback hook is the same as useMemo hook with the only different of that this hook will cache the function (first paramter for useCallback) without calculating the value. Also the function can accept parameters unlike in useMemo.

To use useCallback you need to pass parameters:

  • A Function definition that needs to be cached.
  • List of dependencies

const cachedFn = useCallback(fn, dependencies)

import { useCallback } from 'react';

export default function ProductPage({ productId }) {
  const handleSubmit = useCallback((orderDetails) => {
    post('/product/' + productId + '/buy', {
      referrer,
      orderDetails,
    });
  }, [productId, referrer]);
Nach dem Login kopieren

When to use useMemo over useCallback

If you'r primarily concerned with optimizing the result of calculation, use useMemo.
If you're primarily concered with preventing unnecessary re-renders due to function changes, use useCallback.

Skipping re-renders of a component

Sometimes you will have a parent component that need to re-render which will result also in the re-render of child component. It's possible to cache a component using memo.

Lets assume we have a Todolist component with theme state, and a List component as child. Whenever the state of theme changes the List Component re-render which is not necessary. to solve this issue use memo.

we wrap the functional component of List with memo.

export default function TodoList({ todos, tab, theme }) {
  // ...
  return (
    <div className={theme}>
      <List items={visibleTodos} />
    </div>
  );
}
Nach dem Login kopieren
import { memo } from 'react';

const List = memo(function List({ items }) {
  // ...
});
Nach dem Login kopieren

Conclusion

In this comprehensive guide we have understand useMemo and useCallback hooks, How to use each one of them, When to use each of them, And explained their benefits for optimizing the performance of React application.

Das obige ist der detaillierte Inhalt von„useMemo' und „useCallback' verstehen: Eine umfassende Anleitung. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!