Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next,js 13: How to adapt useEffect call on root layout?

I want to execute an useEffect call on all pages of my site. Before the Next v13 I called this effect on the _app.ts. On Next v13 the root layout replaces the _app.ts, but it must be server component (therefore we can't use the useEffect hook inside it).

So how can I execute an useEffect on all pages of my site (without execute it separately on each page)?

I thought about create a context and execute the useEffect inside it. But this isn't the best way, since the context api was not created for this purpose. Is there a better solution?

like image 692
Gustavo Polonio Avatar asked Oct 24 '25 05:10

Gustavo Polonio


1 Answers

You could move your useEffect to a client component that is rendered inside of src/app/layout.tsx. This way it will run no matter which page is rendered by the client.

For example, you could update the RootLayout to render it as:

export default async function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <ClientApplication>
          {children}
        </ClientApplication>
      </body>
    </html>
  );
}

Where ClientApplication has the useEffect that you want to trigger on the client for every page:

"use client";

export default function ClientApplication({ children }) {
  useEffect(() => {
    console.log("Client-side effect triggered");
  });

  return children;
}
like image 177
thgaskell Avatar answered Oct 26 '25 20:10

thgaskell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!