3 ms·
React now supports this using Suspense boundaries [0]. Some frameworks (eg. NextJS) already ship variants of it but here is some code you could use in React's d
by n2d4 3y ago
React now supports this using Suspense boundaries [0]. Some frameworks (eg. NextJS) already ship variants of it but here is some code you could use in React's development version:
function MyComponent() {
const promise = ...;
const result = use(promise); // use is like await
// do something
}
function Wrapper() {
return (
<Suspense fallback={<Loading />}>
<MyComponent />
</Suspense>
);
}
You don't need to know this to use it, but the implementation is both interesting and horrifying: The `use` hook checks if the Promise has resolved, and if not, it throws an error that is caught by the Suspense boundary. And because there is no property like `hasResolved` on JS promises, `use` adds one itself. (At least this was how an early draft proposed it, a lot of changes have been done since, and my knowledge might be out of date.)
[0] https://react.dev/reference/react/Suspense https://react.dev/reference/react/Suspense
- valenterry 3y agoThank you, this is exactly what I meant! Awesome that this is already being worked on in react. Yeah, the implementation under the hood seems a bit crazy. Reminds me of how I found out that angular used to call toString on functions to get the parameter names for dependency injection. But honestly, if I can use it without problems as a user, that's what I care most, even if the backend developer in me is horrified about it, haha. But I guess that is mostly Javascripts fault after all.
- eyelidlessness 3y agoThe way Suspense works is actually even a bit more interesting/horrifying: it doesn’t throw an error, it throws a Promise. Which again you don’t need to know to use it, and so it’s a valid implementation detail, but it’s a really odd one.
- SebastianKra 3y agoTo be fair, in js, throwing is the only way a function (aka Hook) can abort the execution of its calling function (aka Component). The decision to avoid a custom compiler is responsible for almost all oddities and downsides of React.
- theteapot 3y agoIs a thing in Vue3 also -- https://vuejs.org/guide/built-ins/suspense.html https://vuejs.org/guide/built-ins/suspense.html