Async Atoms and Suspense Integration
What you'll learn: How Jotai atoms can return promises and automatically work with React Suspense to handle loading states declaratively.
The Promise-Returning Pattern
In Jotai, atoms aren't limited to synchronous values—they can return promises. When an atom's value is a promise, Jotai automatically integrates with React's Suspense boundaries. The component that reads this async atom will suspend (pause rendering) until the promise resolves, letting Suspense show a fallback UI.
This means you don't need to manually track loading states or write conditional rendering logic. The framework handles it for you.
How It Works
import { atom, useAtomValue } from 'jotai';
import { Suspense } from 'react';
// This atom returns a promise
const userAtom = atom(async () => {
const response = await fetch('/api/user');
return response.json();
});
function UserProfile() {
// This will suspend until the promise resolves
const user = useAtomValue(userAtom);
return <div>Welcome, {user.name}!</div>;
}
function App() {
return (
<Suspense fallback={<div>Loading user...</div>}>
<UserProfile />
</Suspense>
);
}
The Magic Behind the Scenes
When useAtomValue encounters an atom with a promise, it throws that promise (yes, actually throws it). React Suspense catches thrown promises, shows the fallback, and re-renders the component once the promise resolves. It's like a try-catch for async operations, built into the rendering flow.
This pattern eliminates the need for useState, useEffect, and loading flags when fetching data.
Key Takeaway: Jotai atoms can return promises, automatically suspending components until data loads—Suspense handles the fallback UI, making async state management declarative and clean.