Next.js Discord

Discord Forum

pass props between template and page

Unanswered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
How do i pass props with app router and not pages router

9 Replies

Spectacled bearOP
pass props from template.tsx to page.tsx
my files are app/ not pages/
no you cannot pass data between template.tsx and page.tsx because they are independently run
you can use cache() for deduplication of queries on the server, then call the query in both template.tsx and page.tsx
or use the context API if you want to pass data on the client-side
Spectacled bearOP
do u have any examples to implement this?
@Spectacled bear do u have any examples to implement this?
context API should be simple right, just use react context

about the cache:

export const getData = cache(async () => {
  console.log("I was run!");
  return "John Doe";
});

// template.tsx
export default async function Template({ children }) {
  const name = await getData();
  return <div>{name} {children}</div>;
}

// page.tsx
export default async function Page() {
  const name = await getData();
  return <div>{name}</div>;
}

although getData is called twice, it's only run once (the console.log only logs once)
Spectacled bearOP
how do i do this with "use client"
@Spectacled bear how do i do this with "use client"
in client components then forget all this cache shenangans. just use react contexts https://react.dev/learn/passing-data-deeply-with-context

export const SomeContext = createContext(null);

// template.tsx
export default function Template({ children }) {
  return <SomeContext.Provider value="John Doe">{children}</SomeContext.Provider>;
}

// page.tsx
export default function Page() {
  const name = useContext(SomeContext);
  return <div>{name}</div>;
}