DEV Community

Discussion on: React 18 server components deep dive

 
xakrume profile image
Ruslan Kh.

Modify the App.client.js file to use cookies:

// App.client.js

import {useState, useEffect} from 'react';
import Message from './Message.server';

function App() {
  const [selectedId, setSelectedId] = useState(() => {
    // Read the initial value from the cookie
    return Number(document.cookie.replace(/(?:(?:^|.*;\s*)selectedId\s*\=\s*([^;]*).*$)|^.*$/, "$1")) || 1;
  });

  useEffect(() => {
    // Update the cookie whenever selectedId changes
    document.cookie = `selectedId=${selectedId}`;
  }, [selectedId]);

  return (
    <div>
      <button onClick={() => setSelectedId(selectedId + 1)}>
        Next
      </button>
      <Message id={selectedId} />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we'll use the useState and useEffect hooks to read the initial selectedId value from a cookie and update the cookie whenever the selectedId changes.

Note that this is a simplified example. In a real application, you would want to use a more robust method for managing cookies, such as the js-cookie library.

Thread Thread
 
tresorama profile image
Jacopo Marrone • Edited

This is from Next.js docs:

"use client" sits between server-only and client code. It's placed at the top of a file, above imports, to define the cut-off point where it crosses the boundary from the server-only to the client part. Once "use client" is defined in a file, all other modules imported into it, including child components, are considered part of the client bundle.

Since Server Components are the default, all components are part of the Server Component module graph unless defined or imported in a module that starts with the "use client" directive.

Good to know:

"use client" does not need to be defined in every file. The Client module boundary only needs to be defined once, at the "entry point", for all modules imported into it to be considered a Client Component.

I was assuming that this behavior is a React thing and not a Next thing.
There are some place where this is explained from a plain React side?