Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React Compiler: Cannot reassign variable after render completes

The immutability rule flags a closure that writes a render-scoped value. Decide whether it is a real bug, a false positive, or a bailout.

~5 min readReact
#React#React Compiler#ESLint#Hooks
A render loop fenced off by a red immutability bar and a ref cell beside it, headline NO REASSIGN

Introduction & Quick Summary

Symptom. With React Compiler enabled, the build or the editor reports an error that names a variable rather than a hook:

code
Error: Cannot reassign variable after render completes Reassigning `memoized` after render has completed can cause inconsistent behavior on subsequent renders. Consider using state instead. 29 | memoized.height !== window.innerHeight 30 | ) { > 31 | memoized = { | ^^^^^^^^ Cannot reassign `memoized` after render completes 32 | width: window.innerWidth,

A close relative is Cannot modify local variables after render completes on the same line, or the compiler silently skipping a component, leaving it unoptimized with no visible error.

Cause. Compiler-powered lint rules treat every value created during render as immutable once render returns. A closure that captures a local and writes to it later — even a closure the render itself returns — is flagged, because the write can happen after React has already used the render output. The rules are react-hooks/immutability and its siblings in eslint-plugin-react-hooks v6 and later, and they fire from the compiler's own analysis rather than from the classic hook rules.

Fix. Decide whether the write is a real bug or a false positive, then fix it with the mechanism that matches.

tsx
// real bug: a mutable slot that should be a ref const cache = useRef<{ width: number; height: number } | null>(null); const getSnapshot = useCallback(() => { if (!cache.current) cache.current = { width: window.innerWidth, height: window.innerHeight }; return cache.current; }, []);
tsx
// false positive on a closure the rule cannot see through function useValue(read: () => boolean) { "use no memo"; // opt this hook out of compilation and linting const getSnapshot = useMemo(() => { let cached: boolean | undefined; return () => (cached ??= read()); }, [read]); return useSyncExternalStore(subscribe, getSnapshot, () => false); }

Core Mechanics, Signatures & Reproducible Setup

React Compiler memoizes components automatically, and to do that safely it has to assume a render is pure: given the same props and state, it produces the same output and touches nothing that outlives the render. Values created inside the component belong to the render; writing to them from a closure that runs later breaks that assumption, and the compiler cannot memoize what it cannot prove.

Enable it in a scratch app and watch the diagnostics, rather than turning it on in a large codebase and drowning:

bash
npx create-vite@latest rc-lab --template react-ts cd rc-lab && npm i -D babel-plugin-react-compiler eslint-plugin-react-hooks
js
// vite.config.ts import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [react({ babel: { plugins: [["babel-plugin-react-compiler", { target: "19" }]] } })], });
js
// eslint.config.js import reactHooks from "eslint-plugin-react-hooks"; export default [ reactHooks.configs["recommended-latest"], ];

Then paste the useSyncExternalStore example from the summary and run npx eslint src. Two errors appear on one line, which is normal: one rule reports the write and another reports the same expression as a modification of a local.

Key Comparison Table

DiagnosticRuleReal cause
Cannot reassign variable after render completesreact-hooks/immutabilitya closure writes to a render-scoped local
Cannot modify local variables after render completesreact-hooks/immutabilitya method call mutates a render-scoped object
Cannot access refs during renderreact-hooks/refsref.current read in the component body
Calling setState during renderreact-hooks/set-state-in-rendera state setter used in the render path
Component missing from the profilercompiler bailoutunsupported syntax, not a rule
Escape hatchScopeCost
useRef instead of a localone valuere-render lost unless another source of truth changes
useState instead of a localone valuetriggers a render, which is usually what was wanted
Move the write into an event handlerone componentthe value must be owned by state or a ref
Derive the value during renderwhole componentnone, and it is the preferred fix
"use no memo" directiveone functionthat function is not optimized
Rule set to warn or offprojectyou also lose the real bugs

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. The write that is a genuine bug

A render-scoped object written from an event handler is the classic case. It "works" because the closure keeps the object alive, and it breaks the moment the component re-renders and the handler closes over a stale copy:

tsx
function Counter() { let count = 0; // new binding every render return <button onClick={() => count++}>{count}</button>; // never visible }

The compiler is right, and the fix is useState unless the value must not trigger a render, in which case useRef is the mechanism designed for it.

2. useSyncExternalStore and the snapshot cache

This is the false positive you will actually meet. The store's getSnapshot must return a stable reference between changes, which requires a cache that is deliberately written from outside the render. The rule flags the write because the closure captures a local:

tsx
function useWindowSize() { const getSnapshot = useMemo(() => { let last = { w: 0, h: 0 }; return () => { if (last.w !== window.innerWidth || last.h !== window.innerHeight) { last = { w: window.innerWidth, h: window.innerHeight }; // flagged } return last; }; }, []); return useSyncExternalStore(subscribe, getSnapshot, () => ({ w: 0, h: 0 })); }

Three honest ways out, in order of preference: move the cache into a useRef so it is clearly not render state; keep it as a module-level cache keyed by window, which is where a global browser value belongs; or opt the hook out with "use no memo" and an ESLint disable comment naming the issue. Do not silence the rule globally for the project, which is the step that turns the compiler from a bug finder into a nuisance.

3. "use no memo" versus disabling the rule

The directive tells the compiler and the linter to leave that function alone, and it is scoped to the function, which is the property that makes it safe. A file-level /* eslint-disable react-hooks/immutability */ disables the check for everything in the file, including the real bug three functions down. Prefer the directive:

tsx
function LegacyChart({ data }: { data: number[] }) { "use no memo"; // unoptimized, still correct, still linted for hooks rules return <canvas data-series={data.join(",")} />; }

Remove it when the pattern is refactored; a directive with no date and no reason becomes permanent.

4. Compiler bailouts are silent

When the compiler cannot compile a function it skips it, and panicThreshold: "none" (the default) means the build does not fail. The component works, just unoptimized, so the only signal is that memoization does not happen. Find them in development with a stricter threshold:

js
["babel-plugin-react-compiler", { target: "19", panicThreshold: "critical_errors" }]

Set it in CI rather than on every developer machine, so an unsupported pattern in a new file fails a pull request instead of quietly degrading performance.

5. Third-party linters report the same diagnostics differently

Oxlint and other Rust-based linters now ship the compiler rules, and their versions disagree with the ESLint plugin on edge cases — logical assignment inside a useMemo-returned closure being the documented example. If a rule fires in one tool and not the other, compare versions before changing the code:

bash
npx oxlint@latest --version npm ls eslint-plugin-react-hooks babel-plugin-react-compiler

The rule implementations converge over time, so a diagnosis of "false positive" should name the tool and version, not the pattern in general.

6. What the rule is protecting

Memoization means React may reuse a previous render's output. If a closure mutates an object that output points at, a reused render can show data from two renders at once, which is the "inconsistent behavior on subsequent renders" in the message. That is why the fix is state, a ref, or a module-level cache, and never // eslint-disable-next-line on the write itself.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Disabling the whole rule set to unblock a build. You lose the actual bugs and the compiler's confidence in your code.
  • Replacing a useRef with a useState to satisfy the rule. The rule is about writes, not about state; that change causes a render loop.
  • Assuming a passing build means the compiler ran. Check the bailout report in CI.
  • Keeping "use no memo" forever. The directive is a marker for a known limitation, not a permanent annotation.
  • Reading ref.current during render to "fix" an immutability error. That is a separate violation and a real bug on the server.
  • Trusting one linter's version of the rule. Oxlint and ESLint differ on recent syntax.
  • Enabling the compiler on a codebase with class components and mutated module state. Start with compilationMode: "annotation" or a directory at a time.

Capture the compiler's diagnostics as JSON in CI and read them with the JSON formatter; when a diagnostic moves between releases, diff the two runs with the text diff tool before you change any code.

Reference: React Compiler and eslint-plugin-react-hooks.

Official references

primary documentation

The React documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.