You are currently looking at the v0.12.0 docs, which are still a work in progress. If you miss anything, you may find it in the older v0.11.0 docs here.
Lazy Components
It's good practice to delay loading the JavaScript required to render components you're not actually showing yet. This helps with performance and makes your application load faster.
React ships with an API for dynamically loading components. In this little guide we'll show you how to dynamically load React components in ReScript.
Note: This section requires the latest @rescript/react bindings to be installed (0.12.0-alpha.2 and above).
ReScript comes with APIs for doing dynamic imports both for single values and for entire modules. These APIs make dynamically importing React components easy.
Let's look at a small example. First we'll define a simple component:
RESCRIPT// Title.res
@react.component
let make = (~text) => {
<div className="title">{text->React.string}</div>
}
Now we can dynamically import the <Title/>
component by passing the result of our dynamic import to React.lazy_
:
RESCRIPT// SomeOtherFile.res
module LazyTitle = {
let make = React.lazy_(() => Js.import(Title.make))
}
let titleJsx = <LazyTitle text="Hello!" />
That's all the code we need! The new <LazyTitle />
component behaves exactly the same as the wrapped <Title />
component, but will be lazy loaded via React's built in lazy mechanism.
You can read more about
Js.import
and dynamic import in ReScript in this part of the documentation.