Performance: Why state management differs in Next.js
This affects how quickly the page can load and update by managing where and when state changes happen in Next.js apps.
'use client'; import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return <button onClick={() => setCount(c => c + 1)}>Count: {count}</button>; } // Embed in Server Component: async function Page() { return <Counter />; } export default Page; // Note: Pure UI state like counters must be client-side, but isolate in small client components to minimize re-renders impact.
import { useState } from 'react'; export default function Page() { const [count, setCount] = useState(0); return <button onClick={() => setCount(count + 1)}>Count: {count}</button>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Client-side state only | Many updates on client | Multiple reflows per update | High paint cost on interaction | [X] Bad |
| Server-side state with server components | Minimal client updates | Single or no reflows on interaction | Low paint cost | [OK] Good |
| Client data fetching in useEffect | Delayed DOM update | Reflow on data arrival | Paint triggered after load | [!] OK |
| Server data fetching in server component | DOM ready with data | No reflows on load | Paint happens once | [OK] Good |
useState in Next.js components?use client directive at the top of a file to mark it as a client component.useState and useEffect.use client -> Option Ause client [OK]"use client";
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
setCount(count + 1)}>
Count: {count}
);
}"use client"; directive enables hooks like useState in this component.export default function Profile() {
const [name, setName] = useState('Guest');
return Hello, {name}
;
}useState but lacks the "use client"; directive at the top.useState only work in client components marked by "use client";.useState manage user input state and handle events.useState for input, server components for data fetch -> Option CPass the test and this pattern moves unknown