Skip to content

Bug: react-hooks/set-state-in-effect: false-positive with ternary #35276

@silverwind

Description

@silverwind

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

Steps To Reproduce

function getWidth(el: HTMLElement) {
  return el.clientWidth;
}

function Component({value}: {value: string}) {
  const [width, setWidth] = useState(0);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setWidth(ref.current ? getWidth(ref.current) : 0);
//  ^^^^^^^^^^^^ Avoid calling setState() directly within an effect
  }, [value]);

  return <div ref={ref}>{value}{width}</div>;
}

Changing the line to setWidth(getWidth(ref.current)); makes the error go away, so it seems the presence of the ternary operator is confusing the rule.

The current behavior

Error is raised.

The expected behavior

No error to be raised.

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