">
 

How to Avoid Overusing useCallback and useMemo in React

Iniciado por joomlamz, Hoje at 02:15

Respostas: 0   |   Visualizações: 1

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.


                     How to Avoid Overusing useCallback and useMemo in React
               




Tópico:
                     How to Avoid Overusing useCallback and useMemo in React
               
Categoria: Tutoriais | FreeCodeCamp Premium
Idioma Principal: Português (Conteúdo de Tecnologia)

Conteúdo do Tutorial / Guia Passo a Passo:
-------------------------------------------------------------------------
If you've spent enough time in the React ecosystem, you'll have likely seen codebases where nearly every function is wrapped with
useCallbackand the computed value is wrapped with
useMemo.

The reason behind this is "memoization equals better performance". But most of the time, this doesn't really translate to better performance, and it often produces code that's harder to debug.

In this article, you'll learn how to structure your code to avoid overusing
useCallbackand
useMemo.

Prerequisites

You should be comfortable with React hooks and components before reading this tutorial. Familiarity with
useState,
useEffect, and
useRefis assumed. You can read the following freeCodeCamp articles if you need a refresher on
useCallbackand
useMemo:

• How to Use the useMemo and useCallback Hooks

• Difference between the useMemo and useCallback Hooks

Table of Contents

• Prerequisites

• What useCallback and useMemo Do

• useMemo

• useCallback

• Problem With Memoization

• The Problematic Page

• How to Move State Down

• Move ProductTable Logic To Its Component

• Move Filtering Logic To Its Component

• Move Search Logic Into Its Component

• Move Filter Chips into Its Component

• The Final SearchPage

• Fix Your Code Before Reaching For These Hooks

• When to Use useCallback and useMemo

• Measure Before You Optimize

• Stabilize References for React.memo Children

• Conclusion

What
useCallbackand
useMemoDo[/b][/size]

Before moving to how to avoid overusing them, we'll look briefly at what these hooks do.

useMemo

useMemocaches the return value of a function between re-renders. Imagine you have a sorted list of items in a component:

interface Item {
name: string;
createdAt: string;
}

function App() {
// == some other states ==
// == some other states ==
const [items, setItems] = useState<Item[]>([]);

const sortedItems = [...items].sort(
(a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
);

return (
<>
<ul>
{sortedItems.map((i) => (
<li key={i.name}>{i.name}</li>
))}
</ul>
</>
);
}

React recomputes
sortedItemsevery time the
Appcomponent re-renders. This means
sortedItemswill be recalculated anytime there are any state changes in the
Appcomponent.

React developers often use
useMemoto cache values like this.

Wrapping it with
useMemoensures that
sortedItemsis only calculated when
itemsactually changes:

const sortedItems = useMemo(() => {
return [...items].sort(
(a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
);
}, [items]);

useCallback

useCallbackcaches the function itself. The function below will be recreated every time some states in the component change:

[code]function App() {
// == some other states ==
// == some other states ==
const [userId, setUserId] = useState(0);

const verifyUser = async () => {
// update a state to show loading
console.log("__ Do something with user id __", userId);
// update a state to remove loading
};

return (
<>
<button onClick={verifyUser}>Verify</button>
</>
);
}
[/code

... [O tutorial continua no link abaixo] ...


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: