Search⌘ K

Performance - Avoiding Heavy Computation

Explore how to optimize React app performance by preventing unnecessary re-renders and expensive computations. Understand using useCallback to memoize callback handlers and useMemo to limit heavy calculations only to necessary updates. This lesson helps you identify when to apply these hooks for better app efficiency without premature optimization.

The list passed to the List component is the same, but the onRemoveItem callback handler isn’t. If the App component re-renders, it always creates a new version of this callback handler. Earlier, we used React’s useCallback Hook to prevent this behavior, by creating a function only on a re-render (if one of its dependencies has changed).

Node.js
const App = () => {
...
const handleRemoveStory = React.useCallback(item => {
dispatchStories({
type: 'REMOVE_STORY',
payload: item,
});
}, []);
...
console.log('B:App');
return (... );
};

Since the callback handler gets the item passed as an argument in its function signature, it doesn’t have any dependencies and is declared only once when the App component initially renders. None of the props passed to the List component should change now. Try it with the combination of memo and useCallback, to search via the SearchForm’s input field. The “B:List” output disappears, ...