What Exactly Is "use Client" In Nextjs?
Written by Eddie ZhangatDecember 26, 2024
Nextjs
use client
How?
typescriptexport const LOG = () => { if (typeof window !== undefined) { console.log('I am on client side'); } if (process.env.NODE_ENV) { console.log('I am on server side'); } };
tsimport { LOG } from '@/lib/LOG'; const Page = () => { LOG(); }; export default Page;
ts'use client'; import { LOG } from '@/lib/LOG'; const Page = () => { LOG(); }; export default Page;
So why nextjs invent it?
-
Full page load: nextjs renders a full page of static HTML on server side, then use js script to append browser features on client side. -
Subsequent navigation: First, what is "subsequent navigation"? I believe nextjs document didn't explain it well. But it sounds like "client navigation" to me, probably it means the Link component in next/link. Anyway, in this case, nextjs directly sends js bundle to browser, this is the real "client side rendering".
Key points
- client components are more than the components use 'use client'
- the components use 'use client' are hydrated on client side
- the components use 'use client' are rendered on server side (at first stage)
- 'use server' can only be used in the components use 'use client'
Extra
tsconst Page = () => { return ( <p> <h3>This is index</h3> </p> ); };