-
Notifications
You must be signed in to change notification settings - Fork 49.6k
Open
Labels
Status: UnconfirmedA potential issue that we haven't yet confirmed as a bugA potential issue that we haven't yet confirmed as a bug
Description
React version: [email protected]
, [email protected]
Steps To Reproduce
- Paste the valid sample from https://react.dev/reference/eslint-plugin-react-hooks/lints/set-state-in-effect#valid into a file.
- Adjust to remove type-errors when using Typescript (should be irrelevant)
- Perform linting with
eslint-plugin-react-hooks
and thereact-hooks/set-state-in-effect
rule enabled
Link to code example:
https://react.dev/reference/eslint-plugin-react-hooks/lints/set-state-in-effect#valid
// ✅ setState in an effect is fine if the value comes from a ref
function Tooltip() {
const ref = useRef(null);
const [tooltipHeight, setTooltipHeight] = useState(0);
useLayoutEffect(() => {
const { height } = ref.current.getBoundingClientRect();
setTooltipHeight(height);
}, []);
}
Typescript variant, with usage:
export function Tooltip(): ReactElement {
const ref = useRef<HTMLDivElement>(null);
const [tooltipHeight, setTooltipHeight] = useState(0);
useLayoutEffect(() => {
const height = ref.current?.getBoundingClientRect().height ?? 0;
setTooltipHeight(height);
}, []);
return <div ref={ref}>{tooltipHeight}</div>;
}
Another similar example that also triggered this error:
function Foo(): ReactElement {
const ref = useRef<HTMLDivElement>(null);
const [isWithinBar, setIsWithinBar] = useState(false);
useLayoutEffect(() => {
setIsWithinBar(ref.current?.closest('.bar') != null);
}, []);
return <div ref={ref} className={isWithinBar ? 'variant-1' : 'variant-2'}>Foo</div>
}
The current behavior
The code, straight out of the valid section of the docs, triggers an ESLint error of react-hooks/set-state-in-effect
:

The expected behavior
Valid usage of useLayoutEffect
to do measurements and DOM checks via refs and setting state should not generate any errors.
Metadata
Metadata
Assignees
Labels
Status: UnconfirmedA potential issue that we haven't yet confirmed as a bugA potential issue that we haven't yet confirmed as a bug