Next.js Discord

Discord Forum

Thoughts about streamlining state management across components

Unanswered
Klaas posted this in #help-forum
Open in Discord
Hey everyone! I stumbled upon something useful and thought I'd share. I've been utilizing the globalThis property to streamline state management across my components.

I found this approach particularly handy due to dealing with a less-than-ideal API endpoint. It packs data for various components like the menu, Instagram feed, news feed, and sponsors into one call. Instead of multiple API requests, I fetch once and store everything in globalThis.

In my layout.js:
export default async function RootLayout({children}) {
    // Fetching combined data from a single API endpoint
    globalThis.siteStructure = await getSiteStructure();

    return (
        <html lang="en">
            <body className={`bg-neutral-100 font-sans antialiased`}>
                <Header data={globalThis.siteStructure.mainmenu}/>
                <main id={"main"}>{children}</main>
                <Footer/>
            </body>
        </html>
    );
}


This way, accessing data like the Instagram feed becomes as simple as:
const {instagram} = globalThis.siteStructure; for a server-side component.

For a client-side component I would parse the data as a prop like shown in the layout.js example:
<Header data={globalThis.siteStructure.mainmenu}/>

Just curious to hear your thoughts on this!

0 Replies