hardFrontend

How do you avoid re-renders with composition instead of memoization?

921 views
01

Understand the problem

Using the children prop to isolate frequently-changing state.

reactperformancecomposition
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Explore the playground snippets

children as a prop isolates re-renders
Run Playground
import { useState, useRef } from 'react';

function Expensive() {
  const renders = useRef(0);
  renders.current++;
  return <p>Expensive subtree rendered <b>{renders.current}</b> time(s)</p>;
}

function Toggle({ children }) {
  const [on, setOn] = useState(false);
  return (
    <div>
      <button onClick={() => setOn((o) => !o)}>{on ? 'On' : 'Off'}</button>
      {children}  {/* created by the parent — not re-rendered when `on` flips */}
    </div>
  );
}

export default function App() {
  return (
    <div style={{ fontFamily: 'sans-serif', padding: 24 }}>
      <Toggle>
        <Expensive />
      </Toggle>
      <p style={{ color: '#666' }}>Toggling does NOT re-render Expensive — no memo, just composition.</p>
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.