React & Modern Frontend (445 Qs)•Part 10: Modern React 18, React 19 & Next.js Patterns (317 - 353)
What is the React Compiler (React Forget)?
The React Compiler (formerly known as React Forget) automatically optimizes your components by adding memoization where needed - eliminating the need for manual useMemo, useCallback, and React.memo.
Before React Compiler
jsx
function TodoList({ todos, filter }) {
// Manual optimization needed
const filteredTodos = useMemo(() => {
return todos.filter(todo => todo.status === filter);
}, [todos, filter]);
const handleToggle = useCallback((id) => {
toggleTodo(id);
}, [toggleTodo]);
return (
<div>
{filteredTodos.map(todo => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={handleToggle}
/>
))}
</div>
);
}
// Need to wrap in React.memo
export default React.memo(TodoList);
With React Compiler
jsx
function TodoList({ todos, filter }) {
// Compiler automatically optimizes this!
const filteredTodos = todos.filter(todo => todo.status === filter);
const handleToggle = (id) => {
toggleTodo(id);
};
return (
<div>
{filteredTodos.map(todo => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={handleToggle}
/>
))}
</div>
);
}
// No React.memo needed!
export default TodoList;
How It Works
- Analyzes code during build time
- Identifies expensive calculations and renders
- Automatically inserts memoization where beneficial
- Preserves React semantics - your code still behaves correctly
Benefits
- ✅ Simpler code - no manual optimization
- ✅ Better performance by default
- ✅ Fewer bugs from incorrect dependencies
- ✅ Easier to maintain and read
- ✅ Works with existing code
Enabling React Compiler
jsx
// next.config.js (Next.js)
module.exports = {
experimental: {
reactCompiler: true
}
}
// vite.config.js (Vite)
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [
react({
babel: {
plugins: [['babel-plugin-react-compiler']]
}
})
]
})
When to Still Use Manual Optimization
jsx
// For external libraries without Compiler support
import { expensiveLibFunction } from 'old-library';
function MyComponent() {
// May still need manual memoization here
const result = useMemo(() => expensiveLibFunction(), []);
return <div>{result}</div>;
}
Compatibility
- Works with React 18.3+ and React 19
- Compatible with TypeScript
- Works with all React hooks
- Supports Server Components and Client Components