Performance - Avoiding Heavy Computation
Learn how the performance can be optimized by avoiding heavy computation.
We'll cover the following...
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).
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, ...