How to Fix the React set-state-in-effect ESLint Error
Calling setState inside useEffect makes the react-hooks/set-state-in-effect rule from eslint-plugin-react-hooks report the error "Calling setState synchronously within an effect can trigger cascading renders". To fix it, replace the setState in the effect with one of four things: a calculation during render, a reset using key, a setState only inside a callback, or a subscription with useSyncExternalStore. If you run ESLint or npm run lint in CI and this error stops the job, this article shows where to change the code. I reproduced four versions of the error in a test environment and confirmed each fix.
The test environment was Ubuntu 24.04 with Node.js 22.23.5. I used react and react-dom 19.3.1, typescript 6.0.3, ESLint 10.16.0, eslint-plugin-react-hooks 7.1.1, and typescript-eslint 8.74.0. For the ESLint config, I added the recommended preset of eslint-plugin-react-hooks (reactHooks.configs.flat.recommended) to the recommended presets of @eslint/js and typescript-eslint. To check runtime behavior, I built the page for development with esbuild 0.28.2, then opened it in Chromium 158 with Playwright 1.63.0. I did not use StrictMode. I did not test the display in editors such as VS Code, oxlint, the ESLint config of Next.js, or projects that use the React Compiler.
The Full Error Message and What It Warns About
For the test, I used the following component. It takes a family name and a given name and displays them as "Neko-da Tama". It stores the displayed text in state and builds it inside useEffect.
import { useEffect, useState } from 'react';
export function FullName({ first, last }: { first: string; last: string }) {
const [fullName, setFullName] = useState('');
useEffect(() => {
setFullName(`${last} ${first}`);
}, [first, last]);
return <p>{fullName}</p>;
}
I ran npx eslint src/bad, and FullName.tsx produced the following error. The path at the start of each line has been replaced with /path/to/app.
/path/to/app/src/bad/FullName.tsx
7:5 error Error: Calling setState synchronously within an effect can trigger cascading renders
Effects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:
* Update external systems with the latest state from React.
* Subscribe for updates from some external system, calling setState in a callback function when external state changes.
Calling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).
/path/to/app/src/bad/FullName.tsx:7:5
5 |
6 | useEffect(() => {
> 7 | setFullName(`${last} ${first}`);
| ^^^^^^^^^^^ Avoid calling setState() directly within an effect
8 | }, [first, last]);
9 |
10 | return <p>{fullName}</p>; react-hooks/set-state-in-effect
The first line means that calling setState synchronously inside an effect can trigger cascading renders. The explanation after it says that the body of an effect should normally do one or both of the following: update external systems with the latest state from React, or subscribe to an external system and call setState in a callback when that external state changes.
With the recommended config, this rule is an error, not a warning. In the test environment, ESLint exited with code 1. A CI job fails on any nonzero exit code, so if you run lint in CI, the job stops here. Type checking (npx tsc -p .) passed without errors for this file.
What "Cascading Renders" Means
I wrapped the component in React's <Profiler> and recorded the displayed text on each commit (each time React applies a render to the screen). The results below are from pressing a button that changes the given name from "Tama" to "Mike".
直す前(useEffect で setFullName)
update 表示「猫田 たま」
update 表示「猫田 みけ」
直した後(レンダーの中で計算)
update 表示「猫田 みけ」
Before the fix, after the button press, React first committed the old text "Neko-da Tama", and then committed again after setFullName ran in the effect. The official documentation for set-state-in-effect also says that changing state immediately inside an effect makes React render again, which adds one avoidable render.
Four Rewrites That Remove the Error
In the test, I wrote four cases that trigger the error and fixed each one.
| What the effect was doing | Fix | Commits before the fix | Commits after the fix |
|---|---|---|---|
| Building a displayed value from props | Calculate it during render | 2 | 1 |
| Clearing an input when props change | Pass a key from the parent |
2 | 1 |
| Showing "loading" before a fetch | Calculate "loading" from the fetch result | 3 | 2 |
| Reading the window width on first render | Subscribe with useSyncExternalStore |
2 | 1 |
The commit counts are, in order: when the name changed, when the cat number changed (lines 2 and 3), and when the page opened. After the fixes, npx eslint --max-warnings 0 src/good reported zero errors and zero warnings for all four files.
Before looking for ways to move setState out of the effect, ask whether the state is needed at all. In three of the four examples in this article, the state that the effect changed (fullName, loading, width) was no longer needed after the fix.
Calculate Values from Props During Render
For the first FullName component, the error went away when I stopped storing fullName as state and built it during render.
export function FullName({ first, last }: { first: string; last: string }) {
const fullName = `${last} ${first}`;
return <p>{fullName}</p>;
}
useState and useEffect are no longer needed. This is the same fix as in the official documentation on values that can be calculated from props or state. When the page first opened, the version before the fix committed an empty display once and then "Neko-da Tama". The version after the fix committed "Neko-da Tama" once from the start.
Let the key Handle Resets When Props Change
This component clears a comment box when the cat number catId changes.
import { useEffect, useState } from 'react';
export function CommentBox({ catId }: { catId: number }) {
const [comment, setComment] = useState('');
useEffect(() => {
setComment('');
}, [catId]);
return <textarea value={comment} onChange={(e) => setComment(e.target.value)} />;
}
Here too, the line setComment('') produced the same error. Before the fix, if I typed "cute" in the comment box and then changed the cat number, the box committed once with "cute" still in it, and the next commit cleared it.
I removed the effect and passed key={catId} from the outer component. The error went away.
import { useState } from 'react';
export function CatPage({ catId }: { catId: number }) {
return <CommentBox key={catId} />;
}
function CommentBox() {
const [comment, setComment] = useState('');
return <textarea value={comment} onChange={(e) => setComment(e.target.value)} />;
}
When key changes, React creates a new component instance, so comment goes back to its initial ''. After the fix, the commit made when the cat number changed was a single commit showing an empty box. This matches the form of the official documentation example that resets all state when a prop changes.
In Data Fetching, setState Inside then Is Fine
This is a common pattern: set "loading" before starting the fetch.
import { useEffect, useState } from 'react';
import { getCat } from '../api';
export function CatName({ catId }: { catId: number }) {
const [name, setName] = useState('');
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
getCat(catId).then((cat) => {
setName(cat.name);
setLoading(false);
});
}, [catId]);
return <p>{loading ? '読み込み中' : name}</p>;
}
getCat is a test helper that returns a name such as "Cat 1" after 20 milliseconds. The error appeared only on line 9, setLoading(true);. The setName and setLoading(false) calls inside the then callback did not produce errors, because they match the case in the error explanation: calling setState inside a callback.
So I stopped storing loading as state. Instead, I compare the ID of the fetched cat with the requested cat ID and calculate loading from that.
import { useEffect, useState } from 'react';
import { getCat, type Cat } from '../api';
export function CatName({ catId }: { catId: number }) {
const [cat, setCat] = useState<Cat | null>(null);
const loading = cat?.id !== catId;
useEffect(() => {
let ignore = false;
getCat(catId).then((result) => {
if (!ignore) setCat(result);
});
return () => {
ignore = true;
};
}, [catId]);
return <p>{loading ? '読み込み中' : cat.name}</p>;
}
The error went away. When I changed the cat number from 1 to 2, the commits were as follows.
直す前
update 表示「猫1」
update 表示「読み込み中」
update 表示「猫2」
直した後
update 表示「読み込み中」
update 表示「猫2」
Before the fix, one commit showed "Cat 1" even though the number was already 2. After the fix, a loading label appears in the same render where the number changes. The cleanup with ignore discards the result of an old fetch. It follows the official data-fetching example.
To Read a Browser Value, Subscribe with useSyncExternalStore
This component displays the window width. The original version reads the initial width inside the effect.
import { useEffect, useState } from 'react';
export function WindowWidth() {
const [width, setWidth] = useState(0);
useEffect(() => {
setWidth(window.innerWidth);
const onResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, []);
return <p>幅: {width}px</p>;
}
The error came from the first call on line 7, setWidth(window.innerWidth);. The setWidth inside the resize callback did not produce an error. When I opened the page with the window 800px wide, it first committed a width of 0px and then 800px.
I rewrote it with useSyncExternalStore, which subscribes to an external value. The error went away.
import { useSyncExternalStore } from 'react';
function subscribe(callback: () => void) {
window.addEventListener('resize', callback);
return () => window.removeEventListener('resize', callback);
}
export function WindowWidth() {
const width = useSyncExternalStore(subscribe, () => window.innerWidth);
return <p>幅: {width}px</p>;
}
The page showed 800px from the first commit, and after I changed the window width to 500px, it showed 500px. The official documentation example for subscribing to an external store also recommends useSyncExternalStore instead of subscribing in an effect. For apps that also render on the server, the useSyncExternalStore reference on server rendering support describes passing a function that returns the server value as the third argument.
If you do not use useSyncExternalStore and keep the logic in an effect, you can set the initial value with useState(() => window.innerWidth) and use the effect only to register the resize listener. In that case, the error did not appear.
Patterns That Don't Trigger the Error, and Patterns That Hide It Without Fixing It
Calling setHeight(rect.height) inside a useLayoutEffect, using a height read from a ref, did not produce an error. The official valid examples also list calling setState inside an effect with a value read from a ref as an acceptable pattern.
Some patterns stop the error without fixing the underlying problem. When I put setFullName inside a function defined in the effect and then called that function, the error no longer appeared.
useEffect(() => {
const update = () => {
setFullName(`${last} ${first}`);
};
update();
}, [first, last]);
However, when I changed the name in the browser, the display still committed "Neko-da Tama" once before showing "Neko-da Mike", just as before the fix. The lint error was gone, but the extra render remained, so this does not fix the problem. The official example that subscribes to an external store also marks the pattern of calling setIsOnline from a function defined in the effect as "Not ideal", and rewrites it with useSyncExternalStore.
Also note that this rule has no automatic fix for --fix. Running npx eslint --fix src/bad left the file unchanged. In the JSON output, both fix and suggestions were null. Which fix to use depends on what the state is for, so compare the four patterns above and rewrite the code accordingly.





