`server-only-context` is a lightweight utility designed to provide request-scoped context specifically for React Server Components (RSC). It helps mitigate the problem of prop drilling in server-side rendering environments by leveraging React's experimental `cache` function to store and retrieve values associated with the current request. This ensures that context values are isolated between different concurrent server requests, which is crucial for multi-user applications. The current stable version, 0.1.0, indicates it's an early-stage project that is actively developed but may still be subject to changes. Its core differentiator is its exclusive design for the server-side, contrasting with traditional React Context which is primarily client-side or hydrates from server-rendered content. It offers a straightforward API to create getter/setter tuples for managing context values.
npm install server-only-contextVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to define server-only context and then set and retrieve values within a React Server Component structure, mimicking a typical page and its child components.
Ensure `setContextValue(value)` is called in both the relevant layout and page components where context values might change due to navigation.
Monitor React's official releases and `server-only-context` updates closely. Be prepared to update dependencies and code if React's experimental APIs change.
Ensure that any component calling `get` or `set` functions derived from `serverContext` is a Server Component. Use `"use client";` directive to explicitly mark client components where this context should *not* be used.
Exercise caution when using in production. Pin to exact versions and thoroughly test after any updates. Consider contributing to help stabilize the API.
Verify that the component where `get*` or `set*` functions are called is a Server Component. Ensure no `"use client";` directive is present in the file or any parent component that directly uses this context.
Ensure you are importing `getLocale` and `setLocale` from the specific file where you defined and exported them (e.g., `import { getLocale } from '@/context/locale';`).Implement `setContextValue(value)` calls in both your server-rendered layout and server-rendered page components to ensure the context is correctly initialized for all request paths, including those initiated by client navigation.