atman_lens
atman_lens

Reputation: 822

How to lazy load map component using useEffect hook for React/Next js site

I placed a Google Maps API component on the index page of my Next js site but it's slowing down the load by a crazy amount (something like 500ms).

Is there a way for me to delay the component until after page load using the useEffect hook or in another concise way?

I want to increase the loading speed (and performance score) of the site.

export default function Home() {
  return (

    <div className={styles.main}>
      <Layout>
        <main className={styles.content}> 

          **<div className={styles.mapContainer}>
            <Map  className={styles.map}/>**

          </div>
        </main>
      </Layout>
    </div>

  )
}

Upvotes: 0

Views: 6699

Answers (1)

jered
jered

Reputation: 11581

Next.js provides a dynamic helper that will only load the component when it would render to the page.

https://nextjs.org/docs/advanced-features/dynamic-import

import dynamic from 'next/dynamic'

const Map = dynamic(() => import('components/MapOrWhatever'));

export default function Home() {
  return (
    <div className={styles.main}>
      <Layout>
        <main className={styles.content}> 
          <div className={styles.mapContainer}>
            <Map  className={styles.map}/>
          </div>
        </main>
      </Layout>
    </div>
  )
}

You can also specify options for the dynamic function as the second argument:

const Map = dynamic(() => import('components/MapOrWhatever'), {
    ssr: false, // do not render this on the server side render
    loading: () => <div>Loading Map...</div>, // placeholder component
});

If you want to delay rendering (and therefore loading) your component until a specific time, then yes, you could use an effect or other hook to toggle rendering the map. As an example:

export default function Home() {
  const [showMap, setShowMap] = React.useState(false);

  React.useEffect(() => {
    // Set the map to load 2 seconds after first render
    const timeOut = setTimeout(() => setShowMap(true), 2000);

    return () => clearTimeout(timeOut);
  }, []);

  // <Map> will only load when showMap is true
  return (
    <div className={styles.main}>
      <Layout>
        <main className={styles.content}> 
          {showMap && <div className={styles.mapContainer}>
            <Map  className={styles.map}/>
          </div>}
        </main>
      </Layout>
    </div>
  )
}

In practice, it's better to dynamically load components that are hidden behind some kind of interaction, like changing tabs in the app to load a new route, or clicking a "View Map" button. Putting it behind a setTimeout isn't very productive and you're just artificially delaying the loading of components arbitrarily without really thinking it through. But, I've included it as an example to show how dynamic components only load once they should render.

Upvotes: 5

Related Questions