Middle
Tell me about caching in React — useMemo, useCallback, and so on.
sobes.tech AI
Answer from AI
In React, caching with hooks useMemo and useCallback helps optimize performance by preventing unnecessary calculations and re-creation of functions during re-renders.
-
useMemo memoizes the result of a computation, reusing it if dependencies haven't changed. This is useful for heavy computations or creating objects that shouldn't be recreated unnecessarily.
-
useCallback memoizes a function, returning the same reference if dependencies haven't changed. This is important when passing functions to child components to avoid unnecessary re-renders.
Example:
const MyComponent = ({ items }) => {
const filteredItems = React.useMemo(() => {
return items.filter(item => item.active);
}, [items]);
const handleClick = React.useCallback(() => {
console.log('Clicked');
}, []);
return (
<ChildComponent items={filteredItems} onClick={handleClick} />
);
};
Here, filteredItems is recalculated only when items change, and handleClick retains its reference between renders, helping optimize child component performance.