Performance: Request memoization
Request memoization improves page load speed by avoiding repeated data fetching and reduces server load and client wait times.
export async function getServerSideProps(context) { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data1: data, data2: data } }; }
export async function getServerSideProps(context) { const res1 = await fetch('https://api.example.com/data'); const data1 = await res1.json(); const res2 = await fetch('https://api.example.com/data'); const data2 = await res2.json(); return { props: { data1, data2 } }; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Duplicate fetch calls | Multiple fetch triggers | Multiple reflows due to delayed data | Higher paint cost from repeated updates | [X] Bad |
| Single fetch with memoization | Single fetch triggers | Single reflow after data arrives | Lower paint cost with stable data | [OK] Good |
cache function that wraps async functions to memoize their results.cache(async () => await fetch(...)), which matches const cachedFetch = cache(async () => await fetch('/api/data')).getData()?
import { cache } from 'react';
const getData = cache(async () => {
console.log('Fetching data');
return await fetch('/api/data').then(res => res.json());
});
await getData();
await getData();cache function memoizes the async function result, so the fetch and console.log run only once.import { cache } from 'react';
const getData = async cache(() => {
return await fetch('/api/data').then(res => res.json());
});cache function must wrap the async function, not be called inside the async declaration.async cache(() => ...) is invalid syntax; it should be cache(async () => ...).cache memoizes each unique URL separately.cache with a function that takes the URL as argument and memoizes internally -> Option APass the test and this pattern moves unknown