Coding exercise: debug unnecessary component rendering in React.

React practical coding · Experienced

Model answer

First prove there is a problem: open React DevTools Profiler, record, and see which components render and why (turn on "Record why each component rendered"). Then fix the cause, not the symptom.

Common causes and fixes: a new object, array or function created on every render passed to a memoised child, state kept too high in the tree, and context values that change on every render.

// Problem: Child re-renders whenever Parent does, because onSave is a new function each time
function Parent() {
  const [text, setText] = useState('');
  const onSave = () => save(text);
  return (<>
    <input value={text} onChange={(e) => setText(e.target.value)} />
    <Child onSave={onSave} />
  </>);
}

// Fix 1: memoise the child and keep props stable
const Child = memo(function Child({ onSave }) { return <button onClick={onSave}>Save</button>; });
// (inside Parent)
const onSave = useCallback(() => save(text), [text]);

// Fix 2 (often better): move the typing state into its own small component,
// so keystrokes only re-render the input and nothing else.

Do not wrap everything in memo by default: it costs memory and comparisons. Measure first, and also check that keys are stable and that you are not storing derived values in state. React Compiler can automate some of this where it is enabled.

Tips

Practise it yourself in the React and Angular code playground.

Learn this topic

React.js Full Course: Beginner to Advanced .

Sign in to add your own answer.

More questions