AI Hints
Home›React Tutorial›Memoization
React · Lesson 57 of 120

memo

Skip re-renders.

⏱ 2 min read▶ Video at 46:47🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

When a parent renders, its children render too, even if nothing they use has changed. Memo lets a component skip that, when its props are the same as last time.

  • Parent renders
  • Children render
  • memo skips

A memoized list

Normally, when a parent renders, all its children render too. Memo wraps a component, and skips rendering when its props are the same as last time. Here, typing a note renders App, but the list's items haven't changed. We type a five letter note. Run it. The list rendered only once.

App.jsxjsx
import { useState, memo } from "react";
const ProductList = memo(function ProductList({ items }) {
  console.log("ProductList rendered");
  return <ul>{items.map(p => <li key={p}>{p}</li>)}</ul>;
});
const BIKES = ["Trail 500", "City 200", "Volt 7"];
export default function App() {
  const [note, setNote] = useState("");
  return (
    <div>
      <input id="n" value={note} onChange={e => setNote(e.target.value)} placeholder="Gift note" />
      <ProductList items={BIKES} />
    </div>
  );
}
Output
ProductList rendered
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"type": "#n", "text": "Happy"}]

The React Compiler

The new React Compiler adds this kind of memoization for you, automatically, at build time. In projects that use it, you'll rarely write memo, use memo, or use callback by hand. It still helps to know what they do.

keyvalue
Compilermemoizes for you
Whenbuild time
Resultless manual memo
Stillknow the ideas

Summary

Memo skips re-rendering when props are unchanged. Next, the rules of hooks.

Key takeaways
  • memo(Component)
  • Same props, skip
  • Compiler helps
Next up: Rules of Hooks — top level only