DEV Community

Railson Ferreira de Souza
Railson Ferreira de Souza

Posted on

How to use Chakra UI with Next.js 13 (React Server Components)

Next.js 13 was released a short time ago, bringing great news, the /app directory, which works with React Server Components.

"Today, many components from npm packages that use client-only features do not yet have the directive" (Rendering: Server and Client Components | Next.js)

How can we use those components while we enjoy the new features available in /app directory?

This is quite easy to answer, here's a shortcut for the code that would work with Chakra UI:

chakra-client-components.js

"use client"
export * from "@chakra-ui/react";
Enter fullscreen mode Exit fullscreen mode

So instead of importing from "@chakra-ui/react" in your code, you should import from "./chakra-client-components".

That's all folks πŸ‘‹

Top comments (6)

Collapse
 
mohammedak1991 profile image
Mohammed Abdul Khader • Edited

question: doesnt this make every component a client component then? beating the purpose of using nextjs 13

Collapse
 
raiitto profile image
Railson Ferreira de Souza • Edited

Yes and No. I've read that it is possible to mix Server Components with Client Components, for sure all Chakra components still being Client Components in this short solution, but in the other hand, Next.js 13 has many other new features besides Server Components.

Hopefully Chakra UI will be fully compatible with Server Components as soon as possible.

Collapse
 
ikhomje profile image
Nextdev

And which file I should wrap with ChakraProvider? As there are no "app.tsx" file now.

Collapse
 
raiitto profile image
Railson Ferreira de Souza

Good question, in the /app directory it could be placed in layout.tsx

import { ChakraProvider } from './chakra-client-components';

export default function RootLayout({ children }) {
  return (
    <html>
      <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      </head>
      <body>
        <ChakraProvider>{children}</ChakraProvider>
      </body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

"Note: You should render providers as deep as possible in the tree [...]" - Next.js

Reference:
beta.nextjs.org/docs/rendering/ser...

Collapse
 
ikhomje profile image
Nextdev

Thank you for the reply. I am doing exactly like this. It is working but I was wondering if there is any other way to do this.

Collapse
 
mohammedak1991 profile image
Mohammed Abdul Khader

Im the biggest fan ever of chakra, but I feel like if tailwind css has support in server components, so should chakra ui, i understand if the custom hooks such as useDisclosure and everything need to be in a client component but in other situations it should work..