A component renders for one of these reasons:
- It mounts, which is the first render.
- Its own state changes through a
useStatesetter or auseReducerdispatch. - A context it reads changes.
- Its parent re-renders.
The last point is often misunderstood. By default, when a component re-renders, all its children re-render too. This happens whether or not their props changed. Props changing is not a separate trigger. If you wrap a child in memo, React can skip it when its props are shallowly equal, meaning each prop is the same by Object.is.
If you set state to the same value, by Object.is, React can bail out. That means it skips the re-render.
Re-rendering means calling the component function again. It does not mean the DOM changes, because React only commits differences. Re-renders are usually cheap. They are only a problem when they are slow and frequent.
- A component re-renders when its own state changes through a setter or dispatch.
- When a parent re-renders, its children re-render by default.
- A component that reads a context re-renders when that context value changes.
memoskips a re-render when the props are shallowly equal.- Rendering is not the same as updating the DOM.
Read more