react icon indicating copy to clipboard operation
react copied to clipboard

Bug: `use` hook throws error in Client Component without SSR when used in child component

Open gitivon opened this issue 1 year ago • 1 comments

React version: 19.0

Steps To Reproduce

When using the use hook with a Promise context in a child component, it throws an error about async/await not being supported in Client Components. However, the same pattern works in the parent component.

Link to code example:

Environment

  • React version: 19.0.0
  • Build tool: Vite
  • No SSR implementation
import { createContext, use, useState } from "react";
import "./App.css";

const AppCtx = createContext(new Promise<string>((r) => r("React")));

const Child = () => {
  const value = use(AppCtx);
  return <>{use(value)}</>;
};

function App() {
  const [value] = useState(new Promise<string>((r) => r("React")));
  return (
    <AppCtx value={value}>
      Hello
      <Child />
    </AppCtx>
  );
}

export default App;

The current behavior

Uncaught Error: async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding 'use client' to a module that was originally written for the server.

The expected behavior

Since this is a client-side only application without any SSR, the use hook should work consistently in both parent and child components when handling Promise contexts.

gitivon avatar Dec 06 '24 04:12 gitivon

You can use Suspense to wrap the suspended component and ensure React only tries to render it when it is ready. I agree the current error message is not the best, though.

BetoFrega avatar Dec 06 '24 20:12 BetoFrega

Can you try this without an uncached Promise e.g. by moving the Promise creation outside of the render of App?

eps1lon avatar Dec 09 '24 20:12 eps1lon

You can use Suspense to wrap the suspended component and ensure React only tries to render it when it is ready. I agree the current error message is not the best, though.

it's useful

gitivon avatar Dec 14 '24 17:12 gitivon