Skip to content

Instantly share code, notes, and snippets.

@mike-at-redspace
Last active February 10, 2023 11:10
Show Gist options
  • Save mike-at-redspace/29eb5d79007e83d936ed28b14d50fa36 to your computer and use it in GitHub Desktop.
Save mike-at-redspace/29eb5d79007e83d936ed28b14d50fa36 to your computer and use it in GitHub Desktop.
React lazy and Suspense
import React, { lazy, Suspense } from 'react'
import useIntersectionObserver from './useIntersectionObserver'
const AboveTheFold = () => (
<div>
<h1>This is the AboveTheFold content</h1>
<p>It will be rendered immediately when the page loads</p>
</div>
)
const BelowTheFold = lazy(() => import('./BelowTheFold'))
const App = () => {
const [belowTheFoldRef, belowTheFoldIntersecting] = useIntersectionObserver({ threshold: 0.5 })
return (
<div>
<AboveTheFold />
<div ref={belowTheFoldRef}>
{belowTheFoldIntersecting ? (
<Suspense fallback={<div>Loading Below The Fold component...</div>}>
<BelowTheFold />
</Suspense>
) : (
<div>Loading Below The Fold component...</div>
)}
</div>
</div>
)
}
export default App
import { useState, useEffect, useRef } from 'react'
const useIntersectionObserver = (options) => {
const [intersecting, setIntersecting] = useState(false)
const targetRef = useRef(null)
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setIntersecting(true)
observer.disconnect()
}
})
}, options)
if (targetRef.current) {
observer.observe(targetRef.current)
}
return () => {
observer.disconnect()
}
}, [options])
return [targetRef, intersecting]
}
export default useIntersectionObserver
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment