#is the layout.tsx file SSR
1 messages · Page 1 of 1 (latest)
The layout.tsx file in Next.js can be used for both Server-Side Rendering (SSR) and Client-Side Rendering (CSR), depending on how you implement it.
If you use React's useEffect() hook inside your layout, it means you are implementing Client-Side Rendering. This is because useEffect() runs after the component mounts, which happens in the browser, not on the server. Here's an example of using useEffect() inside a Next.js page:
import { useEffect } from 'react'
export default function Page() {
useEffect(() => {
// This code runs client-side
}, [])
return <div>Hello World</div>
}
However, it's important to note that Layout components do not receive the searchParams prop. This is because a shared layout is not re-rendered during navigation which could lead to stale searchParams between navigations. When using client-side navigation, Next.js automatically only renders the part of the page below the common layout between two routes.
Also, inside your layout, you can fetch data on the client-side using useEffect or a library like SWR. But because this file is not a Page, you cannot use getStaticProps or getServerSideProps currently.
import useSWR from 'swr'
import Navbar from './navbar'
import Footer from './footer'
export default function Layout({ children }) {
const { data, error } = useSWR('/api/navigation', fetcher)
if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>
return (
<>
<Navbar links={data.links} />
<main>{children}</main>
<Footer />
</>
)
}
Sources:
- Client-Side Rendering (https://nextjs.org/docs/pages/building-your-application/rendering/client-side-rendering)
- Layout's do not receive
searchParams(https://nextjs.org/docs/app/api-reference/file-conventions/layout) - Data Fetching in Layout (https://nextjs.org/docs/basic-features/layouts)