Search code examples
reactjslazy-loading

Mixing dynamic imports with if conditions


I know that currently we can use a dynamic import inside an es-module to lazily import code:

import * as React from 'react'

const SmileyFace = React.lazy(() => import('./smiley-face'))

function App() {
  return (
    <div>
      <React.Suspense fallback={<div>loading...</div>}>
        <SmileyFace />
      </React.Suspense>
    </div>
  )
}

But I want to not put that import statement on top - but inside an if block because i don't want to load it unless my viewport size is bigger than mobile.

so can i do this ?

import * as React from 'react'

let SmileyFace = null;
let isMobile = innerWidth > 400;

function importIfNecessary(){
  if(isMobile) {
     SmileyFace = React.lazy(() => import('./smiley-face')) 
  }
}

function App() {
  return (
  isMobile ? <>Bland Mobile code</> : 
    <div>
      <React.Suspense fallback={<div>loading...</div>}>
        <SmileyFace />
      </React.Suspense>
    </div>
  )
}

Thanks for reading my question.


Solution

  • The smiley will only import if it is being rendered.

    // parent.js
    import * as React from 'react'
    const SmileyFace = React.lazy(() => import('./Smiley')) 
    
    let isMobile = innerWidth > 400;
    
    function App() {
      return (
          isMobile ? <>Bland Mobile code</> : <React.Suspense fallback={<div>loading...</div>}><Smiley /></React.Suspense>
      )
    }
    
    // Smiley.js
    export const Smiley = () => {
      return (
        [... whatever your smiley face is]
      )
    }
    

    (Not tested, let me know if it works). There's probably a cleaner solution, but this should get you started.