0
0
NextJSframework~8 mins

Data cache behavior in NextJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Data cache behavior
MEDIUM IMPACT
This affects page load speed and interaction responsiveness by controlling how data is reused or refetched in Next.js apps.
Fetching data on client-side navigation
NextJS
import useSWR from 'swr'; const fetcher = url => fetch(url).then(res => res.json()); const { data } = useSWR('/api/data', fetcher);
Caches data in memory and reuses it on navigation, reducing network calls and speeding up rendering.
📈 Performance Gainsingle network request per data change, faster UI updates, reduces blocking by 50-80%
Fetching data on client-side navigation
NextJS
useEffect(() => { fetch('/api/data').then(res => res.json()).then(setData); }, []);
Fetches data on every client navigation without caching, causing repeated network requests and slower UI updates.
📉 Performance Costblocks rendering for 100-300ms per navigation, triggers multiple network requests
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
No cache, fetch on every navigationMinimal0High due to delayed paint[X] Bad
Client-side cache with SWR or React QueryMinimal0Low, immediate paint with cached data[OK] Good
Rendering Pipeline
Data cache behavior affects the critical rendering path by reducing the need for network fetches before painting content. Cached data allows the browser to skip waiting for server responses, speeding up style calculation and layout.
Network
Style Calculation
Layout
Paint
⚠️ BottleneckNetwork latency and blocking data fetches before paint
Core Web Vital Affected
LCP, INP
This affects page load speed and interaction responsiveness by controlling how data is reused or refetched in Next.js apps.
Optimization Tips
1Cache data to avoid repeated network requests on navigation.
2Use libraries like SWR or React Query for automatic caching and revalidation.
3Monitor network requests in DevTools to ensure caching reduces fetches.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of caching data in a Next.js app?
AReduces repeated network requests and speeds up page rendering
BIncreases bundle size significantly
CTriggers more reflows during rendering
DBlocks rendering until all data is refetched
DevTools: Network
How to check: Open DevTools, go to Network tab, navigate pages and observe repeated API calls for data endpoints.
What to look for: Multiple identical fetch requests indicate no caching; fewer requests with fast responses indicate effective caching.