// App.client.jsimport{useState,useEffect}from'react';importMessagefrom'./Message.server';functionApp(){const[selectedId,setSelectedId]=useState(()=>{// Read the initial value from the cookiereturnNumber(document.cookie.replace(/(?:(?:^|.*;\s*)selectedId\s*\=\s*([^;]*).*$)|^.*$/,"$1"))||1;});useEffect(()=>{// Update the cookie whenever selectedId changesdocument.cookie=`selectedId=${selectedId}`;},[selectedId]);return(<div><buttononClick={()=>setSelectedId(selectedId+1)}>
Next
</button><Messageid={selectedId}/></div>);}exportdefaultApp;
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.
"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?
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Modify the App.client.js file to use cookies:
In this example, we'll use the
useStateanduseEffecthooks to read the initialselectedIdvalue from a cookie and update the cookie whenever theselectedIdchanges.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.
This is from Next.js docs:
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?