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
const Home = lazy(() => import("./home")); const Products = lazy(() => import("./home/products"));
Waiting component:
function WaitingComponent(Component) { return props => ( <Suspense fallback={<Loading />}> <Component {...props} /> </Suspense> ); }
Can I do something like this?
const Home = lazy(() => { setTimeout(import("./home"), 300); });
You just add some @keyframes animations to Fallback component, and delay its display either by setTimeout and a state flag, or by pure CSS ( animation-fill-mode and -delay used here).
Suspense is a component required by the lazy function basically used to wrap lazy components. Multiple lazy components can be wrapped with the suspense component. It takes a fallback property that accepts the react elements you want to render as the lazy component is being loaded.
The lazy component should then be rendered inside a Suspense component, which allows us to show some fallback content (such as a loading indicator) while we're waiting for the lazy component to load. The fallback prop accepts any React elements that you want to render while waiting for the component to load.
Suspense is not a data fetching library. It's a mechanism for data fetching libraries to communicate to React that the data a component is reading is not ready yet. React can then wait for it to be ready and update the UI. At Facebook, we use Relay and its new Suspense integration.
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:
const Home = lazy(() => { return new Promise(resolve => { setTimeout(() => resolve(import("./home")), 300); }); });
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:
const Home = lazy(() => { return Promise.all([ import("./home"), new Promise(resolve => setTimeout(resolve, 300)) ]) .then(([moduleExports]) => moduleExports); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With