DEV Community

Taegeun Moon
Taegeun Moon

Posted on

Q) Why can't `use` hook be called inside a closure?

I am learning about the new use hook that will be introduced in React 18.3.

The RFC states that use hook can be called conditionally, but also enforces that it must be directly called inside a Component or Hook. (Conditionally suspending on data)

The RFC is taking two examples, each represents valid and invalid case.

function ItemsWithForLoop() {
  const items = [];
  for (const id of ids) {
    // ✅ This works! The parent function is a component.
    const data = use(fetchThing(id));
    items.push(<Item key={id} data={data} />);
  }
  return items;
}

function ItemsWithMap() {
  return ids.map((id) => {
    // ❌ The parent closure is not a component or Hook!
    // This will cause a compiler error.
    const data = use(fetchThing(id));
    return <Item key={id} data={data} />;
  });
}
Enter fullscreen mode Exit fullscreen mode

But how could React ever know (not the compiler) if the use hook was called inside map?
It leads to my question that why this restriction is imposed.

Top comments (0)