Skip to content

Bug: react-hooks/set-state-in-effect false positive on valid example in docs #34858

@Svish

Description

@Svish

React version: [email protected], [email protected]

Steps To Reproduce

  1. Paste the valid sample from https://react.dev/reference/eslint-plugin-react-hooks/lints/set-state-in-effect#valid into a file.
  2. Adjust to remove type-errors when using Typescript (should be irrelevant)
  3. Perform linting with eslint-plugin-react-hooks and the react-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:

Image

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

No one assigned

    Labels

    Status: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions