Skip to content

Instantly share code, notes, and snippets.

@ali-master
Created August 9, 2024 20:14
Show Gist options
  • Save ali-master/a6dee7cc151b8e171d9cb1fbf70e6d60 to your computer and use it in GitHub Desktop.
Save ali-master/a6dee7cc151b8e171d9cb1fbf70e6d60 to your computer and use it in GitHub Desktop.
NextJS Server Only Context API

NextJS Server Only Context API

Tiny wrapper around cache to have request-scoped context for server components. No more prop drilling!

Note: when navigating on the client side the layout is not re-rendered, so you need to set the context both in the page and in the layout.

export const [getLocale, setLocale] = ServerContext("en");
export const [getUserId, setUserId] = ServerContext("");
import { setLocale, setUserId } from "@/context";

export default function UserPage({ params: { locale, userId } }) {
  setLocale(locale);
  setUserId(userId);
  return <MyComponent />;
}
import { getLocale, getUserId } from "@/context";

export default function MyComponent() {
  const locale = getLocale();
  const userId = getUserId();

  return (
    <div>
      Hello {userId}! Locale is {locale}.
    </div>
  );
}
import { cache } from "react";
export function ServerContext<T>(defaultValue: T): [() => T, (v: T) => void] {
const getRef = cache(() => ({ current: defaultValue }));
const getValue = (): T => getRef().current;
const setValue = (value: T) => {
getRef().current = value;
};
return [getValue, setValue];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment