Next.js 13 - Accessing search params from a deeply nested server component in the same route segment?

447 views Asked by At

I know that search params are accessible in page component props, but can the deeply-nested, non-page server components inside the same route segment also access search params somehow? For example, let's assume a scenario. We have the following component structure:

RouteSegmentPage
  ServerComponentLevel1
    ...
    ServerComponentLevelN
      LeafClientComponent
AnotherRouteSegmentPage
  ...

RouteSegmentPage displays a rich page that consists of many nested non-page child components, all in the same route segment. ServerComponentLevelN needs to fetch some data using search params. How can we achieve this without prop drilling search params from RouteSegmentPage to all the way down to ServerComponentLevelN?

Note: ServerComponentLevelN needs to stay as server component.

1

There are 1 answers

1
Chakib Salah On

Found a workaround for this here https://github.com/vercel/next.js/discussions/51818 by icyJoseph

The work around is to basically avoid using hooks , and stick to only js .

  1. create store
// app/store.tsx
const createStore = () => {
  let data: string | null = null;

  const setData = (next: string) => {
    data = next;
  };

  const getData = () => {
    return data;
  };

  return { setData, getData };
};

export const store = createStore();
  1. Save search params into the store .
// app/[foo]/[bar]/page.tsx

import { Outer } from "../../Outer";
import { store } from "../../store";

export default function Page({
  params,
}: {
  params: { foo: string; bar: string };
}) {
  const { foo, bar } = params;
  store.setData(`/${foo}/${bar}`);
  return <Outer />;
}

  1. Access your searchParms saved in store

import { store } from "./store";

export const Inner = () => {
  return <div>{store.getData()}</div>;
};