2

This is a Lazy Route component I wrote a while ago (code below).

This is what it does:

  • It initially render a lazyLoading = true state to show some spinner or something.
  • Then on useEffect it will dynamic import() a component module and set the LazyComponent state. Like setLazyComponent(module)
  • Then it will turn the loading to false and render <LazyComponent.default />

Note: It works as intended.

My question is:

I've tried to do the following:

  • Set the default property to the state. As in setLazyComponent(module.default). Since SomeComponent, which is the component that is being lazy loaded has a single default export.
  • Then I should be able to render just <LazyComponent/> instead of <LazyComponent.default/>
  • But it does not work.

And I get this error:

enter image description here

Why does it not work? All the rest of the code is the same. The only change I'm trying to make is the place where I access the default property.

import React, { useEffect, useState } from 'react';
import styled from 'styled-components';

const LS = {};

LS.Container_DIV = styled.div`
`;

async function lazyRender() {
  const module = await import("./SomeComponent");
  return new Promise((resolve) => {
    resolve(module);
  });
}

function LazyRoute(props) {
  console.log('Rendering LazyRoute...');

  const [lazyLoading,setLazyLoading] = useState(true);
  const [LazyComponent,setLazyComponent] = useState(null);

  useEffect(() => {
    async function getLazyComponent() {
      const module = await lazyRender();
      setLazyComponent(module);
      setLazyLoading(false);
    }
    getLazyComponent();
  },[]);

  return(
    lazyLoading ?
      <div>I am Lazy Loading....</div>
    : <LazyComponent.default {...props}/>
  );
}

export default React.memo(LazyRoute);
cbdeveloper
  • 27,898
  • 37
  • 155
  • 336

0 Answers0