Categories
React

React Rendering

  1. It Always Re-renders
  2. How to Prevent Re-renders
    1. memo()
    2. Flatten props
    3. useMemo()
    4. useCallback()
    5. Stateful Higher-Order Dual-Context
  3. Ref:

It Always Re-renders

By default, when the state of the component changes, this component and all its children re-render. 

But React updates a text node only when there’s visual change. “Rendering” of react component is not the same with “updating the DOM”.

How to Prevent Re-renders

memo()

Wrapping a component with memo prevents the entire subtree of this component from re-rendering in response to parent render.

Flatten props

Flatten props to primitive values, otherwise the non-primitive values are compared by reference, which will be refreshed in every render and thus trigger re-render of children component even with memo().

useMemo()

If possible, declare the non-primitive prop outside the component to prevent re-generation on each render.

Otherwise, use useMemo() to cache the result of its calculation instead of returning a new value on every render. For non-primitive values, it will return the same reference. Any change detected in the dependency list will trigger new calculation, and for non-primitive values, means a new reference.

useCallback()

Similar to useMemo(), but for functions.

Stateful Higher-Order Dual-Context

Keep state variables and state-update functions in separate Contexts, so that state-update functions do not change their reference between renders.


Ref:

https://alexsidorenko.com/blog/react-render-cheat-sheet/

Leave a comment