I have a dynamic form component that renders inputs based on an object prop. I have 6 lazy-loaded components. I would like to prefetch the non-rendered components as soon as the page is displayed so the next inputs appear immediately if requested (it is a multiple page form).
<Suspense fallback={null}>
{fields.map((field, i) => (
<Field key={i}>
{generateField(field, onChange)}
</Field>
))}
</Suspense>
After reading several blogs, it seems there are 3 ways of doing it:
1: by adding a /* webpackPrefetch: true */ comment in the import declaration
const Select = lazy(() =>
import(/* webpackPrefetch: true */ "components/form/select")
);
2: A import declaration followed by a lazy loading
const SelectPromise = import("components/form/select");
const Select = React.lazy(() => SelectPromise);
3: Same thing but achieved in one line with a fonction:
function lazyPreload(component) {
const Component = lazy(component);
Component.preload = component;
return Component;
}
const Select = lazyPreload(() => import("components/form/select"));
// ps: I've seen this function can be used to trigger the prefetch on demand by calling Select.preload() on. mouseHover for example. So does it mean this function automatically prefetch the component or that I have to trigger the prefetching myself?
Among these three options, which is the most efficient technique? The form is constantly re-rendered when the user enters a value (it changes the main form, which then sends back the value, so the inputs are generated again, etc. Not sure if this has an impact on prefetching here).