-
Starter Code: CodeSandBox
Discussion points:
- The
Moviescomponent causesMovieto re-render although its props don't change.- What is the difference between the "React render phase" and the "graphical rendering" of DOM nodes to pixels on the screen?
- Fix the unnecessary re-renders.
- TODO: Add
onClick={handleMovieClick}as prop toMoviecomponent -> Problem resurfaces. Why? How can you fix it? - Is there a simpler fix to the problem?
- The
-
Solution Code: CodeSandBox
- The
Moviecomponent gets memoized viaReact.memo
- The
-
React.memois a higher-order-component which shallowly compares props before rendering to prevent unnecessary re-renders. -
The second argument of
React.memo, i.e. a function of the form(prevProps, nextProps) => true if same result should prevent re-render. false otherwise.can be used to refine the props comparison. -
Tipp: Set the
displayNameproperty of your component to make debugging easier (i.e. with React DevTools):import React from 'react'; const MyComponent = React.memo(() => { // ... }) MyComponent.displayName = 'MyComponent';
- Problem: A passed handler reference will change on every render. If passed to children it will cause them to rerender frequently even with a wrapped
React.memo. - Solution: The
useCallbackhook lets you keep the same callback reference between re-renders