Next.js Discord

Discord Forum

Lazy Loading Dropdown Menu

Unanswered
Yacare Caiman posted this in #help-forum
Open in Discord
Yacare CaimanOP
I'm creating several dropdown filters where the options are from my DB. I want to only load them once someone opens the dropdown menu.

I'm following the docs for the lazy loading, this code specifically:

'use client'
 
import { useState } from 'react'
import dynamic from 'next/dynamic'
 
// Client Components:
const ComponentA = dynamic(() => import('../components/A'))
const ComponentB = dynamic(() => import('../components/B'))
const ComponentC = dynamic(() => import('../components/C'), { ssr: false })
 
export default function ClientComponentExample() {
  const [showMore, setShowMore] = useState(false)
 
  return (
    <div>
      {/* Load immediately, but in a separate client bundle */}
      <ComponentA />
 
      {/* Load on demand, only when/if the condition is met */}
      {showMore && <ComponentB />}
      <button onClick={() => setShowMore(!showMore)}>Toggle</button>
 
      {/* Load only on the client side */}
      <ComponentC />
    </div>
  )
}


I'm noticing with the load on demand option the data is getting loaded every time it's opened. I only want to load on the first appearance. am I approaching this wrong? should I just use something like useEffect instead?

0 Replies