Nextjs 15 hướng dẫn sử dụng lazy load
Lazy load giúp app nhanh hơn và giúp chúng ta làm app mượt hơn
Đầu tiên chúng ta sẽ sử dụng hook như sau : src\hooks\Lazyload.tsx
import { useEffect } from "react";
// Custom Hook để lazy load dữ liệu khi phần tử được cuộn tới
function useLazyLoad(ref, callback, loaded) {
useEffect(() => {
if (!loaded && ref.current) {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
callback();
observer.unobserve(ref.current); // Ngưng theo dõi sau khi load
}
},
{
threshold: 0.1,
root: null,
rootMargin: '100px 0px', // preload sớm hơn một chút
}
);
observer.observe(ref.current);
return () => observer.disconnect();
}
}, [loaded, ref, callback]);
}
export default useLazyLoad;
Tiếp theo chúng ta cần áp dụng vào trong page.js :
'use client';
import useLazyLoad from '@/hooks/Lazyload';
import React, { useEffect, useRef, useState } from 'react';
export default function Page() {
const [users, setUsers] = useState([]);
const [videos, setVideos] = useState([]);
const userRef = useRef(null);
const videoRef = useRef(null);
const [userLoaded, setUserLoaded] = useState(false);
const [videoLoaded, setVideoLoaded] = useState(false);
useLazyLoad(userRef, async () => {
try {
const data = await fetch("https://jsonplaceholder.typicode.com/users");
const datajson = await data.json();
console.table(datajson);
setUsers(datajson);
setUserLoaded(true);
} catch (error) {
console.error('Lỗi ' + error)
}
}, userLoaded)
// Sử dụng hook để lazy load video
useLazyLoad(videoRef, () => {
fetch('https://truyenvideo.com/api/video/relatepost/134')
.then((res) => res.json())
.then((data) => {
setVideos(data || []);
setVideoLoaded(true);
})
.catch((err) => console.error('Lỗi fetch video:', err));
}, videoLoaded);
return (
<div>
<div ref={userRef} className="listname">
<h2>Danh sách người dùng:</h2>
<ul>
{users.length > 0
? users.map((user) => <li key={user.id}>{user.name}</li>)
: <li>Đang tải hoặc chờ cuộn tới...</li>}
</ul>
</div>
<div ref={videoRef} className="title" style={{ marginTop: '100vh' }}>
<h2>Danh sách video:</h2>
<ul>
{videos.length > 0
? videos.map((item) => <li key={item.id}>{item.name || item.title}</li>)
: <li key={1}>Đang tải hoặc chờ cuộn tới...</li>}
</ul>
</div>
</div>
);
}
Ở đây mình dùng ref để xác định phần tử gọi đến useLazyload