Next.js - unstable_noStore() Function



The unstable_noStore() Function

The Next.js unstable_noStore() function is used to opt out of static rendering and indicate a particular component should not be cached. This is useful for components that are not meant to be cached, such as a modal or a chat component.

Syntax

The syntax for the unstable_noStore() function is as follows:

import { unstable_noStore as noStore } from 'next/cache';
 
export default async function ServerComponent() {
  noStore();
  const result = await db.query();
}

Parameters

The unstable_noStore() function accepts no parameters.

Return Value

The unstable_noStore() function does not return any value.

Key Points

  • The unstable_noStore() is a legacy API and no longer recommended. It's still supported for backward compatibility.
  • Instead of using unstable_noStore(), you can use cache: 'no-store' on a fetch() call.
  • The unstable_noStore is preferred over export const dynamic = 'force-dynamic' as it is more granular and can be used on a per-component basis
  • Using unstable_noStore inside unstable_cache will not opt out of static generation. Instead, it will defer to the cache configuration to determine whether to cache the result or not.

Example 1

The code below, we defined a dynamic API route that fetches user data. We are using unstable_noStore() to opt out of static generation for this route. This means that the data will not be cached and will be fetched on every request.

// app/api/user/[id]/route.ts

import { unstable_noStore } from 'next/cache';
import { fetchUserData } from '@/app/utils/db';
import { NextResponse } from 'next/server';

export async function GET(
    request: Request,
        { params }: { params: { id: string } }
    ) {
        // Opt out of caching for this route
        unstable_noStore();
    
    try {
        const userData = await fetchUserData(params.id);
        return NextResponse.json(userData);
    } catch (error) {
        return NextResponse.json(
        { error: 'Failed to fetch user data' },
        { status: 500 }
        );
    }
}

Example 2

The code below shows how to use unstable_noStore() to opt out of static generation for a specific component. This means that the component will not be cached and will be re-rendered on every request.

// app/components/Modal.tsx

import { unstable_noStore } from 'next/cache';

export default function Modal() {
    // Opt out of static generation for this component
    unstable_noStore();
    
    return <div>Modal</div>
}
Advertisements