Loading skeleton for layout.tsx
Answered
Large oak-apple gall posted this in #help-forum
Large oak-apple gallOP
Hi,
Is it possible to add
Is it possible to add
loading.tsx file for layout.tsx file, so I could use a skeleton for sidebar to improve user experience while loading the shell?Answered by joulev
you can use
Suspense to add the loading component for any server components, for example loading skeleton for layout.tsx can be implemented like belowimport { Suspense } from "react";
import { cookies } from "next/headers";
import Loading from "./layout-loading";
async function getUser() {
const nextCookies = cookies().getAll();
await new Promise((resolve) => setTimeout(resolve, 3000));
return { name: "John Doe", cookies: nextCookies };
}
async function LayoutToBeSuspensed({ children }: React.PropsWithChildren) {
const user = await getUser();
return (
<div>
<div>Welcome {user.name}!</div>
{children}
</div>
);
}
export default function Layout({ children }: React.PropsWithChildren) {
return (
<Suspense fallback={<Loading />}>
<LayoutToBeSuspensed>{children}</LayoutToBeSuspensed>
</Suspense>
);
}9 Replies
Chilean jack mackerel
yeah, possible.
there are many ways to do that
@Chilean jack mackerel there are many ways to do that
Large oak-apple gallOP
yo thanks for help!
that told me so much â¤ï¸
European sprat
i suggest reading the docs on Pages and Layout, Route Groups and Loading UI
you can also see a vercel example of instant loading states which can probably be adpated for what you're trying to do:
https://app-router.vercel.app/loading
https://app-router.vercel.app/loading
@Large oak-apple gall Hi,
Is it possible to add `loading.tsx` file for `layout.tsx` file, so I could use a skeleton for sidebar to improve user experience while loading the shell?
you can use
Suspense to add the loading component for any server components, for example loading skeleton for layout.tsx can be implemented like belowimport { Suspense } from "react";
import { cookies } from "next/headers";
import Loading from "./layout-loading";
async function getUser() {
const nextCookies = cookies().getAll();
await new Promise((resolve) => setTimeout(resolve, 3000));
return { name: "John Doe", cookies: nextCookies };
}
async function LayoutToBeSuspensed({ children }: React.PropsWithChildren) {
const user = await getUser();
return (
<div>
<div>Welcome {user.name}!</div>
{children}
</div>
);
}
export default function Layout({ children }: React.PropsWithChildren) {
return (
<Suspense fallback={<Loading />}>
<LayoutToBeSuspensed>{children}</LayoutToBeSuspensed>
</Suspense>
);
}Answer
Large oak-apple gallOP
Thanks!
That’s what I was looking for