Last active
February 10, 2023 11:10
-
-
Save mike-at-redspace/29eb5d79007e83d936ed28b14d50fa36 to your computer and use it in GitHub Desktop.
React lazy and Suspense
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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