Sub topic 3
When Effects Run Relative to Rendering and Commit
Assume you know JavaScript functions and arrays, basic React components and JSX, useState, and the browser DOM.
Effects and the commit
React first renders components to calculate the next UI. It then commits the necessary DOM changes. After the commit, useEffect runs, usually after the browser can paint. Use it for synchronization with systems outside React, such as network requests, subscriptions, or document titles.
useLayoutEffect runs after React changes the DOM but before the browser paints. Use it only when you must measure or adjust layout before the user sees it. Prefer useEffect for ordinary side effects.
import { useEffect } from 'react';
function PageTitle({ title }) {
useEffect(() => {
document.title = title;
}, [title]);
return <h1>{title}</h1>;
}An effect can return a cleanup function. React runs cleanup before the effect runs again and when the component is removed.
Skipping work with memoization
React.memo can skip a child render when its props are shallowly equal. useMemo caches a calculated value, and useCallback caches a function reference. These tools help only when they prevent measurable work, such as an expensive child render.
const Row = memo(function Row({ id, onSelect }) {
return <li onClick={() => onSelect(id)}>Row {id}</li>;
});
const handleSelect = useCallback(id => setSelected(id), []);A newly created function or object is a different reference, so it can defeat memoization.
Strict Mode and pure rendering
In development, Strict Mode may call render logic more than once to reveal mutations and other impure behavior. A render function must produce the same JSX for the same props and state. Do not change global data, start subscriptions, or perform requests while rendering.
Fiber and concurrent rendering
Fiber is React’s internal unit of work for a component tree. It stores relationships, state, and pending work. Fiber lets React split rendering into smaller tasks.
With concurrent rendering, React can pause, discard, or restart render work before committing it. A transition marks non-urgent updates, allowing urgent interactions to stay responsive. Only committed work changes the DOM.
Measuring re-renders
Use the React DevTools Profiler to record an interaction. Inspect which components rendered, how long they took, and whether memoization removed useful work. Measure before adding memo, useMemo, or useCallback.
| Tool | Main question |
|---|---|
| Profiler | Which renders cost time? |
Exercise
When should you choose useEffect instead of useLayoutEffect?
Show answer
Choose useEffect unless work must run after the DOM update but before the browser paints, such as measuring layout.