Server state and client state help manage data in web apps. Server state is data from the server, client state is data stored in the browser.
Server state vs client state in NextJS
/* Server state example: fetching data in Next.js server component */ export default async function Page() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return <div>{data.message}</div>; } /* Client state example: using useState in a React component */ import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); }
Server state is usually fetched asynchronously and can be shared across users.
Client state is local to the user and changes instantly on interaction.
export default async function Page() { const res = await fetch('https://api.example.com/user'); const user = await res.json(); return <h1>Hello, {user.name}</h1>; }
import { useState } from 'react'; export default function Toggle() { const [on, setOn] = useState(false); return <button onClick={() => setOn(!on)}>{on ? 'ON' : 'OFF'}</button>; }
This example shows client state with a counter button that updates instantly on click. It also shows server state by fetching a post title from an API and displaying it.
import { useState } from 'react'; // Client state: count button function Counter() { const [count, setCount] = useState(0); return ( <div> <h2>Client State Example</h2> <button onClick={() => setCount(count + 1)} aria-label="Increment count"> Count: {count} </button> </div> ); } // Server state: fetch message export async function getServerSideProps() { const res = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const post = await res.json(); return { props: { title: post.title } }; } export default function Page({ title }) { return ( <div> <Counter /> <h2>Server State Example: {title}</h2> </div> ); }
Server state updates when you fetch new data from the server or reload the page.
Client state updates immediately on user actions without needing to reload.
In Next.js, server state can be fetched in server components or data fetching methods like getServerSideProps.
Server state is data from the server, shared and fetched asynchronously.
Client state is local data in the browser, updated instantly by user actions.
Use server state for data from APIs, client state for UI interactions.