Lesson 18 +10 XP

Opting Out of Caching & Uncached Data

Opting Out of Caching & Uncached Data

While fetch() integrates directly with Next.js caching, applications often query databases directly using ORMs like Prisma, Drizzle, or Mongoose without calling fetch().

1. Opting Out of Caching with noStore()

To force a component or function to bypass caching when making direct database or third-party SDK calls, use connection() or unstable_noStore() from next/cache:

import { unstable_noStore as noStore } from 'next/cache';
import db from '@/lib/db';

export default async function LiveMetrics() {
  // Opt out of caching for this component's scope!
  noStore();

  // Direct database query now runs dynamically on EVERY request
  const activeCount = await db.session.count({ where: { active: true } });

  return <div>Active Users: {activeCount}</div>;
}

2. Request Memoization for Non-fetch Queries (React.cache)

Because direct ORM database queries do not use fetch(), Next.js cannot automatically deduplicate them.

To memoize custom async functions, wrap them with React's built-in cache() utility:

// lib/getUser.ts
import { cache } from 'react';
import db from '@/lib/db';

// React.cache memoizes this database call per request!
export const getUser = cache(async (userId: string) => {
  console.log('Fetching user from DB for ID:', userId);
  return await db.user.findUnique({ where: { id: userId } });
});

Now, if three components call getUser('123') during a single render pass, the database query runs only once.

Cache Management Strategy Matrix

Data Source / ToolRequest MemoizationPersistence CachingOpt-out Method
Native fetch()AutomaticAutomatic (Data Cache){ cache: 'no-store' }
Prisma / Drizzle ORMWrap with React.cache()None by defaultCall noStore() in component
Third-Party SDK (Stripe/Firebase)Wrap with React.cache()None by defaultCall noStore() in component

TL;DR

  • Use noStore() from next/cache to force dynamic rendering for non-fetch database calls.
  • Use React.cache() to memoize and deduplicate custom async database queries per request.
  • Direct database queries do not persist in the Next.js Data Cache by default.
  • Combining React.cache() with noStore() ensures efficient, fresh data fetching.