React
The working principle of Suspense
INHO LEE
May 14th, 2025
Index
Core principle: Promise throwing
The key concept for understanding how Suspense works is that it “throws a Promise.” In JavaScript, throwis typically used to raise errors, but React takes a creative approach by repurposing it for this mechanism.
Three States and Promises
When fetching data, there are three possible states:
- The data has not been requested yet
- The data is currently being requested
- The data has finished loading
The React team cleverly adopted the approach of handling thrown Promises during the above data-fetching process.
// Suspense pseudo-code
function Suspense({ children, fallback }) {
let content;
try {
content = children;
} catch (promise) {
if (promise instanceof Promise) {
// when promise resolved, calling rerender
promise.then(() => rerender());
// when promise pending
return fallback;
}
throw promise; // throw error when promise rejected
}
return content;
}