REACT & NEXT.JS / 7. DATA FETCHING & CACHING
Data Fetching, Server Actions & Caching
Getting data in and out — the right way for each scenario
EXPLANATION
Next.js extends the native fetch API with caching options.
fetch() caching options:
• fetch(url) → cached by default (like getStaticProps)
• fetch(url, { cache: "no-store" }) → always fresh (like getServerSideProps)
• fetch(url, { next: { revalidate: 60 } }) → revalidate every 60 seconds (ISR)
Server Actions: async functions that run on the server, called from client components.
Mark with "use server" directive. Used for form submissions, mutations.
This replaces API routes for simple mutations.
When to use what:
• Server Component fetch → reading data on initial page load
• Server Action → form submissions, mutations (create/update/delete)
• API Route (route.ts) → webhooks, third-party integrations, REST API
• React Query / SWR → client-side data that needs refetching, pagination
React Query handles: loading/error states, caching, background refetch, pagination, optimistic updates. Use it for any client-side data fetching.DIAGRAM
Data fetching decision tree:
Need data for initial page render?
└── YES → Server Component fetch()
├── Static? → cache: "force-cache" (default)
├── Dynamic? → cache: "no-store"
└── Revalidate? → next: { revalidate: N }
User submits a form / mutation?
└── Server Action ("use server")
└── revalidatePath() to refresh the page
Client-side fetching (after load)?
└── React Query / SWR
└── handles loading, error, caching, refetch
External webhook / REST API?
└── API Route (app/api/.../route.ts)CODE