Skip to content

Bug: The ESLint react-hooks/preserve-manual-memoization rule warns against optional chaining operator #35577

@4eb0da

Description

@4eb0da

eslint-plugin-react-hooks version: 7.0.1

Steps To Reproduce

const Test = ({ obj }) => {
    const onClick = useCallback(() => {
        if (obj?.id) {
            console.log(obj.id);
        }
    }, [obj?.id]);

    return (
        <button onClick={onClick}>
            Hello
        </button>
    );
};

The current behavior

Compilation Skipped: Existing memoization could not be preserved

React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected. The inferred dependency was `obj`, but the source dependencies were [obj?.id]. Inferred less specific property than source.

The expected behavior

No errors

This can be fixed in several trivial ways:

  1. Use obj?.id in all places
  2. Introduce the variable:
const onClick = useCallback(() => {
    const id = obj?.id;
    if (id) {
        console.log(id);
    }
}, [obj?.id]);

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