When does react component re-renders? What can cause the re-render, and how to prevent unnecessary renders? Here is a quick cheat sheet you can refer to whenever you find yourself asking these questions.
This article serves as a table of content for a Visual Guide to React Rendering series. Every section of the cheat sheet links to the correspondent chapter of the guide that explores a topic in depth.
Standard rendering and memo
By default, when the state of the component changes, this component and all its children re-render. You can wrap React component with memo
to prevent an entire subtree from re-rendering.
A Visual Guide To React Rendering - It Always Rerenders (Chapter 1)
Primitive vs Non-primitive props
Non-primitive values in javascript are compared by reference.
{display: "flex"} === {display: "flex"} // false
Keep that in mind when passing props to memoized components. Memoized components re-render when their props change.
A Visual Guide To React Rendering - Props (Chapter 2)
Stable reference with useMemo
You can preserve a reference to a non primitive value with useMemo
. It won't change on re-renders.
A Visual Guide To React Rendering - useMemo (Chapter 3)
Stable reference with useCallback
You can preserve a reference to a function with useCallback
A Visual Guide To React Rendering - useCallback (Chapter 4)
Rendering and Context
The component right under your context provider should probably use memo
A Visual Guide To React Rendering - Context (Chapter 5)
Rendering and DOM
React component render does not mean DOM update. React is smart enough to update only those parts of DOM that need to change.
A Visual Guide To React Rendering - DOM (Chapter 6)
Originally published at alexsidorenko.com
Articles on the topic:
- A (Mostly) Complete Guide to React Rendering Behavior - Mark Erikson
- Fix the slow render before you fix the re-render - Kent C. Dodds
- Before You memo() - Dan Abramov
Top comments (5)
I do the same using Redux and Redux thunk to renders API, but Iwould like to know if you can do a real simple sample using like that way but taking in memo the response to display the same information changing just condition of the request. I means, avoiding another request and making it to the memo hook already stored in redux.
Link in post is 404: dev.to/blog/react-render-always-re...
Thanks a lot for mentioning this ❤️
Great article and examples! Thanks for sharing.
i like it, I left you a comment on Linkedin! ^^