Skip to content

Instantly share code, notes, and snippets.

@mmyoji
Last active February 7, 2025 05:14
Show Gist options
  • Save mmyoji/b6066d896314435cc17e263ff411218d to your computer and use it in GitHub Desktop.
Save mmyoji/b6066d896314435cc17e263ff411218d to your computer and use it in GitHub Desktop.
minimal example of `use()` API w/ react@19
import { Suspense, use } from 'react';
function Messages({ fetchMessages }: { fetchMessages: Promise<string[]> }) {
// Promise must be initialized outside the component currently.
// see: https://react.dev/blog/2024/12/05/react-19#new-feature-use
//
// This doesn't work;
// ```
// const messages = use(new Promise<string[]>((resolve) => {
// setTimeout(() => {
// resolve(['foo', 'bar', 'buz']);
// }, 1000);
// });
// ```
const messages = use(fetchMessages);
return (
<ul>
{messages.map((m) => (
<li key={m}>{m}</li>
))}
</ul>
);
}
export function App() {
const fetchMessages = new Promise<string[]>((res) => {
setTimeout(() => {
res(['foo', 'bar', 'buz']);
}, 1000);
});
/**
* Real example:
* ```
* const fetchMessages = fetch("/api/messages").then(async (res) => {
* if (res.ok) {
* return (await res.json()) as string[];
* }
*
* throw new Error((await res.json()).message);
* });
* ```
*/
return (
<Suspense fallback={<div>Loading...</div>}>
<Messages fetchMessages={fetchMessages} />
</Suspense>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment