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.

Introduction & Quick Summary
Symptom. With React Compiler enabled, the build or the editor reports an error that names a variable rather than a hook:
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.
// 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;
}, []);// 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:
npx create-vite@latest rc-lab --template react-ts
cd rc-lab && npm i -D babel-plugin-react-compiler eslint-plugin-react-hooks// 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" }]] } })],
});// 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
| Diagnostic | Rule | Real cause |
|---|---|---|
Cannot reassign variable after render completes | react-hooks/immutability | a closure writes to a render-scoped local |
Cannot modify local variables after render completes | react-hooks/immutability | a method call mutates a render-scoped object |
Cannot access refs during render | react-hooks/refs | ref.current read in the component body |
Calling setState during render | react-hooks/set-state-in-render | a state setter used in the render path |
| Component missing from the profiler | compiler bailout | unsupported syntax, not a rule |
| Escape hatch | Scope | Cost |
|---|---|---|
useRef instead of a local | one value | re-render lost unless another source of truth changes |
useState instead of a local | one value | triggers a render, which is usually what was wanted |
| Move the write into an event handler | one component | the value must be owned by state or a ref |
| Derive the value during render | whole component | none, and it is the preferred fix |
"use no memo" directive | one function | that function is not optimized |
Rule set to warn or off | project | you 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:
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:
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:
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:
["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:
npx oxlint@latest --version
npm ls eslint-plugin-react-hooks babel-plugin-react-compilerThe 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
useRefwith auseStateto 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.currentduring 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 documentationThe React documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related React guides
All React guidesReact: Too many re-renders. React limits the number of renders
A setter runs during render and schedules another render. Fix the invoked handler, the unstable dependency, or the prop-to-state copy.
React 19 Ref Cleanup Functions and forwardRef Deprecation
ref is a normal prop now and a ref callback may return a cleanup function, which breaks every implicit-return callback. Migration steps and the leak it fixes.
React 19 Hydration Mismatch: Error 418 and 421 Root Causes
React discards the server HTML as soon as the first client render differs. The deterministic-value fixes for #418, the attribute mismatch behind #421, and how to read the diff.
React Maximum Update Depth Exceeded: Finding the Update Loop
Fifty nested updates and React gives up. The loop is always a new identity: an inline object in a dependency array, a setState in render, or a selector that returns a fresh array.
More in React
All React guidesThe guides filed next to this one in React, in library order.