Is there a better way to do the following (having a component return null)?
In my Page
component I need to update my pageTitle
state that is rendered in a component further up the tree.
layout.tsx:
import { PageTitleProvider } from "@/contexts/page-title-context";
import Breadcrumbs from "../ui/breadcrumbs";
import PageTitle from "@/app/ui/page-title";
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<>
<div>
<div className="lg:pl-72">
<main>
<PageTitleProvider>
<div className="bg-white px-4 pt-10 lg:px-8">
<Breadcrumbs />
<h1>
<PageTitle />
</h1>
</div>
<div>{children}</div>
</PageTitleProvider>
</main>
</div>
</div>
</>
);
}
page.tsx:
import SetPageTitle from "@/app/ui/set-page-title";
export default async function Page() {
return (
<>
<SetPageTitle pageTitle={"Overview"} />
<div>More stuff here...</div>
</>
);
}
set-page-title.tsx:
"use client";
import usePageTitle from "@/contexts/page-title-context";
import { useEffect } from "react";
export default function SetPageTitle({ pageTitle }: { pageTitle: string }) {
const { setPageTitle } = usePageTitle();
useEffect(() => {
setPageTitle(pageTitle);
}, [pageTitle, setPageTitle]);
return null;
}
Can I get rid of return null
?
2
Answers
Okay I got some ideas from the Next.js discord.
Posting one of them that I think is a good candidate for solving this problem.
I haven't tested this yet so it's in concept mode at the moment. But should work though.
Use a client component with an existing list of titles:
So far I think this is better than the
useEffect
/return null
approach from my question.Why not just call
setPageTitle()
in<Page>
?Your code for
SetPageTitle
isn’t really a Component (since it isn’t really returning JSX).You could make SetPageTitle into a hook that you could then use from within
<Page>
:and then use
useSetPageTitle()
in<Page>
but I don’t see any real benefit over simply usingsetPageTitle()
directly in<Page>