Sub topic 1
Why Components Re-render
Prerequisites
You should know function components, JSX, useState, useEffect, props, and JavaScript reference values such as objects, arrays, and functions.
Why components re-render
A render is React calling a component function to calculate its next user interface. A component re-renders when its state changes, when its parent re-renders, or when a context value it reads changes. React then compares the new result with the previous result and updates the DOM where needed.
A parent re-render does not always mean that every child must do expensive work. By default, though, React calls child components again. First find out whether those renders are actually slow.
Measure first with the Profiler
Use the React DevTools Profiler to record an interaction, such as typing or opening a panel. Select a commit to see which components rendered and how long their rendering took. Look for repeated expensive renders, rather than trying to eliminate every render.
The Profiler answers two questions:
- Which interaction is slow?
- Which components consume the rendering time?
Optimize only after you have a measured target. A component that renders often can still be harmless if each render is cheap.
Referential equality: when two values count as the same
React commonly compares values with Object.is. Primitive values such as strings and numbers compare by value. Objects, arrays, and functions compare by reference:
Object.is({ color: 'blue' }, { color: 'blue' }); // false
const options = { color: 'blue' };
Object.is(options, options); // trueTwo separate object literals contain the same data but have different references. This matters because prop comparisons use references, not deep contents.
Skipping re-renders with React.memo
React.memo returns a component that can skip rendering when its props are unchanged by shallow comparison.
import { memo, useState } from 'react';
const Label = memo(function Label({ text }) {
console.log('render label');
return <p>{text}</p>;
});
export function Counter() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount((n) => n + 1)}>
Count: {count}
</button>
<Label text="Stable text" />
</>
);
}Counter renders after each click, but Label can be skipped because its text prop remains the same. memo does not block renders caused by the component’s own state or context updates.
Exercise
Why does a new object literal usually prevent React.memo from skipping a child render?
Show answer
Each object literal creates a new reference, so shallow comparison sees the prop as changed.