React Compiler Breaking Code — Fix Opt-Out with 'use no memo'
In this fix, you'll learn when and how to opt out of React Compiler. This matters for avoiding compiler bugs with ref-based patterns, and appears in Canvas/WebGL components and third-party integrations.
The Problem
The following code demonstrates the typical mistake:
function Canvas() {
const canvasRef = useRef(null);
useEffect(() => {
const ctx = canvasRef.current.getContext('2d');
}, []);
return <canvas ref={canvasRef} />;
}
// Compiler optimization may break imperative canvas logic
The Fix
Here is the corrected version:
'use no memo';
function Canvas() {
const canvasRef = useRef(null);
useEffect(() => {
const ctx = canvasRef.current.getContext('2d');
}, []);
return <canvas ref={canvasRef} />;
}
// Component works correctly with compiler disabled
Prevention
- Add 'use no memo' at the top of files relying on mutable refs or imperative DOM APIs.
- Use the directive sparingly — only when you identify a compiler-caused bug.
- The directive applies to the entire file below it.
- Components using forwardRef, useImperativeHandle, or Canvas/WebGL often need opt-out.
- Test thoroughly with compiler enabled before excluding components.
Common Mistakes with compiler opt out
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world REACT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro