lazy
For more detailed information about React concepts and APIs, please refer to the official documentation for lazy.
React.lazy
lets you define components that are loaded dynamically, enabling code-splitting and improving performance by only loading components when needed. Lazy components must be rendered inside a Suspense
boundary to handle loading states.
[<ReactLazyComponent>]
attribute
This is the recommended way to define lazy components in Feliz. The attribute automatically wraps the component in React.lazy
and ensures correct transpilation.
Check out the ReactLazyComponent documentation for more details.
React.lazy'
React.lazy'
is a lower-level API that allows you to define lazy components.
To ensure correct rendering:
- use
React.lazy'
to define lazy components andReact.lazyRender
to render them. React.lazy'
must be used aslet
-binding to ensure correct transpilation asconst
in JavaScript.
Suspense Example
Loading the component will take 2 seconds. Then the component will be cached and future reruns will be instant.
Show code
module Example.Suspense
open Feliz
open Fable.Core
/// Lazy load with delay to simulate large component
///
/// Note: Prefer using `[<ReactLazyComponent>]` instead of this approach!
let LazyHello: LazyComponent<unit> =
React.lazy'(fun () ->
promise {
do! Promise.sleep 2000
return! JsInterop.importDynamic "./Counter"
}
)
[<ReactComponent(true)>]
let SuspenseDemo() =
let load, setLoad = React.useState(false)
Html.div [
Html.h3 [ prop.text "Suspense Example" ]
Html.p "Loading the component will take 2 seconds. Then the component will be cached and future reruns will be instant."
if load then
React.Suspense([
React.lazyRender(LazyHello, ())
],
Html.div [ prop.text "Loading..." ]
)
else
Html.button [
prop.text (if load then "Hide Lazy Component" else "Load Lazy Component")
prop.onClick (fun _ -> setLoad(not load))
]
]