Skip to content

Latest commit

 

History

History
76 lines (55 loc) · 2.04 KB

File metadata and controls

76 lines (55 loc) · 2.04 KB
title lazy

Used to lazy load components to allow for code splitting. Components are not loaded until rendered or manually preloaded.

import { lazy } from "solid-js"

const ComponentA = lazy(() => import("./ComponentA"));

function App(props: { title: string }) {
  return (
		<ComponentA title={props.title} />
	)
}

Lazy loaded components can be used the same as its statically imported counterpart, receiving props etc. Lazy components trigger <Suspense>

Preloading data in Nested Lazy Components

Top-level lazy components will automatically be preloaded as well as their preload functions. However, nested lazy components will not be preloaded automatically because they are not part of the route hierarchy. To preload such components, you can use the preload method exposed on the lazy component.

import { lazy } from "solid-js"
import type { Component } from "solid-js"

const Nested = lazy(() => import("./Nested"))

const ComponentWithPreload: Component = () => {
  // preload Nested component when needed
  async function handlePreload() {
	await Nested.preload()
  }

  return (
	<div>
	  <button onClick={handlePreload}>Preload Nested Component</button>
	  <Nested />
	</div>
  )
}

Type Signature

function lazy<T extends Component<any>>(
	fn: () => Promise<{ default: T }>
): T & { preload: () => Promise<T> }

Type Parameters

Name Constraint Description
T Component<any> The component type that will be lazily loaded (including its props).

Parameters

Parameter Type Required Description
fn () => Promise<{ default: T }> Yes A function that returns a dynamic import resolving to the component as the default export.

Returns

Type Description
T & { preload: () => Promise<T> } A renderable component compatible with T that also exposes a preload() method to eagerly load the module.