I am trying to use the new React Lazy and Suspense to create a fallback loading component. This works great, but the fallback is showing only a few ms. Is there a way to add an additional delay or minimum time, so I can show animations from this component before the next component is rendered?
Lazy import now
JavaScript
x
3
1
const Home = lazy(() => import("./home"));
2
const Products = lazy(() => import("./home/products"));
3
Waiting component:
JavaScript
1
9
1
function WaitingComponent(Component) {
2
3
return props => (
4
<Suspense fallback={<Loading />}>
5
<Component {props} />
6
</Suspense>
7
);
8
}
9
Can I do something like this?
JavaScript
1
4
1
const Home = lazy(() => {
2
setTimeout(import("./home"), 300);
3
});
4
Advertisement
Answer
lazy
function is supposed to return a promise of { default: ... }
object which is returned by import()
of a module with default export. setTimeout
doesn’t return a promise and cannot be used like that. While arbitrary promise can:
JavaScript
1
6
1
const Home = lazy(() => {
2
return new Promise(resolve => {
3
setTimeout(() => resolve(import("./home")), 300);
4
});
5
});
6
If an objective is to provide minimum delay, this isn’t a good choice because this will result in additional delay.
A minimum delay would be:
JavaScript
1
8
1
const Home = lazy(() => {
2
return Promise.all([
3
import("./home"),
4
new Promise(resolve => setTimeout(resolve, 300))
5
])
6
.then(([moduleExports]) => moduleExports);
7
});
8