React 19 use hook shim
While waiting for React 19, I still want to release a library that depends on React 19 use hook. Hense, this shim.
npm install react18-use
import { Suspense, useState } from 'react';
import { use } from 'react18-use';
const Counter = ({ countPromise }: { countPromise: Promise<number> }) => {
const count = use(countPromise);
return <p>Count: {count}</p>;
};
const App = () => {
const [countPromise, setCountPromise] = useState(Promise.resolve(0));
return (
<div>
<button
onClick={() =>
setCountPromise(async (prev) => {
await new Promise((resolve) => setTimeout(resolve, 1000));
return (await prev) + 1;
})
}
>
+1
</button>
<Suspense fallback={<p>Loading...</p>}>
<Counter countPromise={countPromise} />
</Suspense>
</div>
);
};
- Only supports promises and contexts.
- It might not work the same as React 19.
- useMemo with use(Context) is highly experimental and not for production.
The examples folder contains working examples. You can run one of them with
PORT=8080 pnpm run examples:01_counter
and open http://localhost:8080 in your web browser.