Course contentsShow
← React
Lesson 1505 of 2,39637. React 19 and BeyondFree lesson

Writing Compiler-Friendly Code

Rules and patterns that help the compiler optimize effectively: pure components and predictable data flow.

Writing Compiler-Friendly Code

What you'll learn: How to structure your React components so the compiler can automatically optimize them without manual intervention.

The Compiler's Sweet Spot

The React Compiler works best when your code follows predictable, "pure" patterns. Think of it like writing for a very literal assistant: the clearer and more consistent your instructions, the better they can help you.

When you write compiler-friendly code, you're essentially making the compiler's job easy by following patterns it can reliably analyze and optimize.

Pure Components: The Golden Rule

Pure components are the compiler's best friend. A pure component always produces the same output given the same props and state—no surprises, no side effects during render:

// ✅ Compiler-friendly: Pure and predictable
function UserCard({ user }) {
  const displayName = user.firstName + ' ' + user.lastName;
  return <div>{displayName}</div>;
}

// ❌ Harder to optimize: Side effects in render
function UserCard({ user }) {
  logAnalytics(user.id); // Side effect!
  return <div>{user.name}</div>;
}

Predictable Data Flow

Keep data flowing in one direction—props down, events up. Avoid hidden dependencies like global variables or external mutations that the compiler can't track:

// ✅ Compiler can track all dependencies
function SearchResults({ query, items }) {
  const filtered = items.filter(item => item.name.includes(query));
  return <List items={filtered} />;
}

// ❌ Hidden dependency on external state
let globalFilter = '';
function SearchResults({ items }) {
  const filtered = items.filter(item => item.name.includes(globalFilter));
  return <List items={filtered} />;
}

Why This Matters

The compiler analyzes your code statically—it reads the text, not the runtime behavior. When you keep logic pure and data flow explicit, the compiler can confidently insert optimizations without breaking anything.

Key Takeaway: Write pure, predictable components with explicit data dependencies—the compiler rewards clarity with automatic optimization, eliminating the need for manual useMemo and useCallback.