Simplifying Lazy Loading in Next.js | by Kithma Marindagoda | Jan, 2022

Reduce component loading time

Keithma Marindagoda
import Child1 from "../Child1";
import Child2 from "../Child2";
import Child3 from "../Child3";
import Child4 from "../Child4";
import Child5 from "../Child5";
const ParentComponent = () => {
return <div>
<Child1/>
<Child2/>
<Child3/>
<Child4/>
<Child5/>
</div>
}
import { useState, useEffect } from "react";const useOnScreen = (ref) => {
const [isIntersecting, setIntersecting] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => setIntersecting(entry.isIntersecting)
);
if (ref.current) {
observer.observe(ref.current);
}
}, []) return isIntersecting;
}
export default useOnScreen
import Child1 from "../Child1";
import Child2 from "../Child2";
import Child3 from "../Child3";
import Child4 from "../Child4";
import Child5 from "../Child5";
import useOnScreen from "../useOnScreen";
const ParentComponent = () => {
const child3Ref = useRef();
const child3RefValue = useOnScreen(child3Ref);
return <div>
<Child1/>
<Child2/>
<div ref={child3Ref}>
{child3RefValue &&<Child3/>}
</div>
<Child4/>
<Child5/>
</div>
}
import Child1 from "../Child1";
import Child2 from "../Child2";
import Child3 from "../Child3";
import Child4 from "../Child4";
import Child5 from "../Child5";
import useOnScreen from "../useOnScreen";
const ParentComponent = () => {
const child3Ref = useRef();
const child3RefValue = useOnScreen(child3Ref);
const [isChild3Ref, setIsChild3Ref] = useState(false);
useEffect(() => {
if (!isChild3Ref)
setIsChild3Ref(child3RefValue);
}, [child3RefValue])
return <div>
<Child1/>
<Child2/>
<div ref={child3Ref}>
{child3RefValue && <Child3/>}
</div>
<Child4/>
<Child5/>
</div>
}
import Child1 from "../Child1";
import Child2 from "../Child2";
import Child4 from "../Child4";
import Child5 from "../Child5";
import useOnScreen from "../useOnScreen";
const Child3 = dynamic(() => import("../Child3"));
const ParentComponent = () => {
const child3Ref = useRef();
const child3RefValue = useOnScreen(child3Ref);
const [isChild3Ref, setIsChild3Ref] = useState(false);
useEffect(() => {
if (!isChild3Ref)
setIsChild3Ref(child3RefValue);
}, [child3RefValue])
return <div>
<Child1/>
<Child2/>
<div ref={child3Ref}>
{isChild3Ref && <Child3/>}
</div>
<Child4/>
<Child5/>
</div>
}

Leave a Comment