Performance: Repository pattern for data access
MEDIUM IMPACT
This pattern affects how data fetching impacts page load speed and interaction responsiveness by centralizing data access logic.
class Repository { async fetchUsers() { const res = await fetch('https://api.example.com/users'); return res.json(); } async fetchPosts() { const res = await fetch('https://api.example.com/posts'); return res.json(); } } export async function getServerSideProps() { const repo = new Repository(); const [users, posts] = await Promise.all([repo.fetchUsers(), repo.fetchPosts()]); return { props: { users, posts } }; } function Page({ users, posts }) { // render users and posts }
export async function getServerSideProps() { const res1 = await fetch('https://api.example.com/users'); const users = await res1.json(); const res2 = await fetch('https://api.example.com/posts'); const posts = await res2.json(); return { props: { users, posts } }; } function Page({ users, posts }) { // render users and posts }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct fetch in multiple components | Multiple fetch calls | Multiple reflows due to delayed content | High paint cost due to blocking | [X] Bad |
| Centralized repository with parallel fetch | Single fetch layer | Single reflow after data ready | Lower paint cost, faster LCP | [OK] Good |
| Repository instantiated inside component | Stable DOM but extra React effects | Extra reflows from re-renders | Moderate paint cost | [!] OK |
| Repository instantiated outside component | Stable DOM and effects | Minimal reflows | Low paint cost | [OK] Good |