I don't quite get how Suspense
works in React. I see Relay uses it, and even in code from another team at the company, only when I ask them how it works, they cannot really answer it (it seems they copied the code from somewhere).
For example, if I have the code:
import {Suspense} from "react";
function App() {
return (
<div className="App">
<Suspense fallback="loading...">
hello world
</Suspense>
</div>
);
}
Is it possible to convert it to some kind of promise, using setTimeout()
so that 3 or 5 seconds later, the loading...
phrase would disappear and the resolved promise that gives "success!" would show up? Is it by the mechanism of a promise?
So far, I see the lazy()
being used, and the current docs says:
Today, Suspense only supports one use case: loading components dynamically with React.lazy. In the future, it will support other use cases like data fetching.
In the future we plan to let Suspense handle more scenarios such as data fetching. You can read about this in our roadmap.
And the roadmap above mentioned the data fetching part:
React 16.x (~mid 2019): The One with Suspense for Data Fetching
and it is using unstable_createResource
to fetch data... so it seems it is supporting data fetching already in 2019, and now is already November 2022. Is it data fetching by some kind of "flag", "state" mechanism but not by promise? It seems somewhat mysterious.
Together with Relay, it only makes it harder to understand, because I tried to understand Suspense well first, and then Relay, but it seems I can't understand Suspense that well to begin with. When I ask coworkers who have used Relay and Suspense in their code, they don't understand it either. They just copied and pasted the code from some where else, which may not be a good scene for software engineering: people do something and they don't know what's really happening.
So the simple question is, how does Suspense work? Is it by making use of promise or something else? And to understand how it works with something else, like lazy()
or Relay, should we consider it "an abstraction" or some kind of "magic", as stated in SICP?
To make the best guess, I am wondering if it is like:
const [isLoading_react_internal__, setIsLoading_react_internal__] = useState(true);
and the setIsLoading_react_internal__
is passed down to the children components, so that they can call setIsLoading_react_internal__()
, and the Suspense is no more than
{isLoading_react_internal__ && {fallback}}
If this really is the case, I hope Facebook or Meta can make it more transparent and perhaps state it in their docs or in StackOverflow so that developers know what is going on. Can any React open source developer confirm how it works here?