2

Is it possible to load a heavy module using React.lazy?

I have a very heavy raw file parsed as string (around 10 mb) and I would like to lazy load it.

After trying:

const Module = React.lazy(() =>
  import("./heavyModule").then((heavyModule) => {
    return (
      <Suspense fallback={null}>
        <SomeComponent src={heavyModule.value} />
      </Suspense>
    );
  })
);

Im getting the following error:

lazy: Expected the result of a dynamic $csbImport() call. Instead received: [object Object]

Demo

Rashomon
  • 5,962
  • 4
  • 29
  • 67

2 Answers2

2

According to you the heavyModule is not a React component

I have a very heavy raw file parsed as string (around 10 mb) and I would like to lazy load it

So you cannot use React.lazy(). Instead i would recommend to import the raw file only where you require it and then render that particular component lazily.

You can try this method :

useEffect(()=> {
 import('./heavyModule').then(data=> {
  // your code
 },[])

Gayatri Dipali
  • 1,171
  • 4
  • 16
0

The official doc states that "In the future we plan to let Suspense handle more scenarios such as data fetching. You can read about this in our roadmap.". The Roadmap mentioned an update to expect in late 2019. But it still is not implemented. This is detailed in this recent issue https://github.com/reactjs/reactjs.org/issues/4829

All in all, if heavyModule does not contain any React component it is simpler to go back to a simpler approach to set the state when the value has been recovered.

componentDidMount() {
  import("./heavyModule").then((heavyModule) => {
    this.setState({value: heavyModule.value})
  })
);
}

And in the view, you can have some conditional rendering

render() {
  const valueRender = value ? <div>{value}</div> : <div>Loading...</div>
  return ({valueRender})
}

widged
  • 2,749
  • 21
  • 25