Skip to content

Move State Down

The Course
•
20 min study

The note's state lives in App. Every keystroke changes App's state, so App re-renders, and so does everything it renders, including the 30 ms chart. The chart doesn't use the note at all:

JSX
export default function App() {
  const [note, setNote] = useState("");

  return (
    <main>
      <h1>Study Hub</h1>
      <Profiler id="Note" onRender={logRender}>
        <label>
          Today's note{" "}
          <input value={note} onChange={(e) => setNote(e.target.value)} />
        </label>
        <p className="muted">{note.length} characters</p>
      </Profiler>
      <Profiler id="Chart" onRender={logRender}>
        <Chart />
      </Profiler>
    </main>
  );
}
State too high React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { Profiler, useState } from "react"; import Chart from "./Chart.jsx"; import { logRender } from "./logRender.js"; // The note's state lives in App, so every keystroke re-renders App, and with // it the Chart. Move the state down to where it's used. export default function App() { const [note, setNote] = useState(""); return ( <main> <h1>Study Hub</h1> <Profiler id="Note" onRender={logRender}> <label> Today's note{" "} <input value={note} onChange={(e) => setNote(e.target.value)} /> </label> <p className="muted">{note.length} characters</p> </Profiler> <Profiler id="Chart" onRender={logRender}> <Chart /> </Profiler> </main> ); } // Pretends to draw a detailed chart: about 30 ms of work every render. export default function Chart() { const start = performance.now(); while (performance.now() - start < 30) { // Busy on purpose. } return ( <section className="panel"> <h2>This week</h2> <p className="muted">Mon 30 · Tue 45 · Wed 20 · Thu 60 · Fri 55 minutes</p> </section> ); } // Logs each render of a <Profiler> subtree: which one, why, and how long it took. export function logRender(id, phase, actualDuration) { console.log(`${id} ${phase}: ${actualDuration.toFixed(0)} ms`); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Before reaching for memo

You could wrap Chart in memo. That works, but it treats the symptom. The cause is that state is higher than it needs to be. Only the input and the character count use note, so move them, and the state, into their own component:

JSX
function NoteBox() {
  const [note, setNote] = useState("");
  return (
    <>
      <label>
        Today's note{" "}
        <input value={note} onChange={(e) => setNote(e.target.value)} />
      </label>
      <p className="muted">{note.length} characters</p>
    </>
  );
}

App then renders <NoteBox /> inside the Note profiler, and has no state. Make the change, clear the console and type two letters.

What you'll see

Only Note update: 0 ms, twice. Typing re-renders NoteBox and nothing else. The chart costs nothing, without any memo.

This is state colocation: keep state as close as possible to the components that use it. It's the cheapest performance fix there is, and it usually makes code clearer too.

When state can't move down: pass children

Sometimes the state must stay high, because a wrapper uses it, such as a panel that can be pinned to stand out. Its contents can still escape the re-render if they're passed in as children:

JSX
function Pinnable({ children }) {
  const [pinned, setPinned] = useState(false);
  return (
    <section className={pinned ? "panel pinned" : "panel"}>
      <button onClick={() => setPinned(!pinned)}>{pinned ? "Unpin" : "Pin"}</button>
      {pinned && <strong> Pinned</strong>}
      {children}
    </section>
  );
}
JSX
<Pinnable>
  <Chart />
</Pinnable>

<Chart /> is created by the parent of Pinnable. When Pinnable's state changes, its children prop is the same element as before, so React doesn't render Chart again. Only components created inside the one that changed are re-rendered.

Exercise

Pin the chart

Add Pinnable to App.jsx, and wrap the chart in it inside the Chart profiler, as above. Click Pin and Unpin, and read the Chart lines. Then change Pinnable so it renders <Chart /> itself, in its body, instead of children, and click again. Explain the difference in the two numbers.

Your working space React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { Profiler, useState } from "react"; import Chart from "./Chart.jsx"; import { logRender } from "./logRender.js"; // The note's state lives in App, so every keystroke re-renders App, and with // it the Chart. Move the state down to where it's used. export default function App() { const [note, setNote] = useState(""); return ( <main> <h1>Study Hub</h1> <Profiler id="Note" onRender={logRender}> <label> Today's note{" "} <input value={note} onChange={(e) => setNote(e.target.value)} /> </label> <p className="muted">{note.length} characters</p> </Profiler> <Profiler id="Chart" onRender={logRender}> <Chart /> </Profiler> </main> ); } // Pretends to draw a detailed chart: about 30 ms of work every render. export default function Chart() { const start = performance.now(); while (performance.now() - start < 30) { // Busy on purpose. } return ( <section className="panel"> <h2>This week</h2> <p className="muted">Mon 30 · Tue 45 · Wed 20 · Thu 60 · Fri 55 minutes</p> </section> ); } // Logs each render of a <Profiler> subtree: which one, why, and how long it took. export function logRender(id, phase, actualDuration) { console.log(`${id} ${phase}: ${actualDuration.toFixed(0)} ms`); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

When state changes, React re-renders the component that owns it and every element that component creates in its JSX. An element that arrived as a prop was created by someone else, during an earlier render, and hasn't changed.

Hint 2: a first step

Do the children version first. A full chart render costs about 30 ms, so a Chart update line far below that means Chart itself didn't run, even though the profiler around it reports that something in its subtree updated. Then move <Chart /> into Pinnable's body and compare.

Show one solution
JSX
<Profiler id="Chart" onRender={logRender}>
  <Pinnable>
    <Chart />
  </Pinnable>
</Profiler>

With children, each click logs Chart update: 0 ms: Pinnable re-rendered (the button and Pinned changed), but the <Chart /> element it was given is the same object as last time, so React skipped it. With <Chart /> written inside Pinnable, each click logs about Chart update: 30 ms: Pinnable creates a new <Chart /> element on every render, so the chart renders again.

The same trick doesn't help if the wrapper removes its children, such as a collapsible panel with {open && children}. Closing it unmounts the chart, and opening it mounts a new one, which costs the full 30 ms. To keep a hidden subtree mounted, use Activity, in this day's last lesson.

Was this article helpful?

Your response is saved on this device.