Skip to content

There's a lot of content on this but I'm confused πŸ˜΅β€πŸ’«. The eslint rule react-hooks/exhaustive-deps throws a warning when we put nested properties from hook-returned objects into the dependency array.Β #34092

@anndreii15-hash

Description

@anndreii15-hash

There's a lot of content on this but I'm confused πŸ˜΅β€πŸ’«. The eslint rule react-hooks/exhaustive-deps throws a warning when we put nested properties from hook-returned objects into the dependency array.

Here's the problem:

// βœ… Allowed
const obj1 = {a: "abc"};
useMemo(() => obj1.a, [obj1.a]);

// βœ… Allowed  
const obj2 = useMemo(() => ({a: "abc"}), []);
useMemo(() => obj2.a, [obj2.a]);

// ❌ Not allowed
const obj3 = useDisclosure();
useMemo(() => obj3.onOpen, [obj3.onOpen]); // missing dependencies: 'obj3'

One of the issues where this is described is #24300 . @gaearon wrote that the reason this is forbidden has to do with useDisclosure's return value needing to be immutable.

However, this does not make sense. In the example above: obj1 is just as mutable as obj3. And overall, I fail to see why the mutability of the enclosing object matters in the first place. In my head, it is the reference to the function onOpen that matters. The fact that I'm allowed to de-structure the value further illustrates this:

// βœ… Allowed
const { onOpen } = useDisclosure();
useMemo(() => onOpen, [onOpen]);

I'm struggling to understand this and can't find any clear reason why we can't have a nested property from a hook-returned object as a dependency.

Originally posted by @florianmartens in #34086

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions