Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use useState in root layout/page in app directory of nextjs 13

In Nextjs 13 - experimental app directory, if I wanted to use useState on the root layout/page I must add ‘use client’ to the code, which effectively prevents all nested components from being server components.. how can I work around this so that I can use useState and still have server components. Thanks to any responders.

like image 802
jon Avatar asked Oct 27 '25 03:10

jon


1 Answers

I don't know if this answers to your question (it's better to add some example code to help users understand your problem)

If you create a Server Component, and in that component you add your Client Component, it works fine. For example

ClientComponent.tsx

"use client";
import {useState} from 'react';

export default function ClientComponent() {
    const [count, setCount] = useState(0);

    return (
        <>
            <h1>Client Component</h1>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </>
    )
}

ServerComponent.tsx

async function getData(){
    const res = await fetch('http://localhost:3000/api/hello');
    return await res.json();
}

export default async function ServerComponent() {
    const data = await getData()

    return (
        <>
            <h1>Server Component</h1>
            <p>{data.name}</p>
        </>
    )
}

Api hello.ts

export default async function handler(req, res) {
  res.status(200).json({ name: 'John Doe' })
}

Your page

import ClientComponent from "./ClientComponent";
import ServerComponent from "./ServerComponent";
export default function Page() {

    return(<>
            <ClientComponent/>
            <ServerComponent/>
        </>
    )
}

In this example ServerComponent is rendered on the server, but ClientComponent on the client so it maintain interactivity

Hope this will help

like image 65
jimpo26 Avatar answered Oct 30 '25 14:10

jimpo26