0
0
NextJSframework~30 mins

Server state vs client state in NextJS - Hands-On Comparison

Choose your learning style9 modes available
Managing Server State and Client State in Next.js
📖 Scenario: You are building a simple blog page using Next.js. The blog posts come from a server, but you want to let users mark posts as favorites on the client side without sending data back to the server.
🎯 Goal: Build a Next.js component that fetches blog posts as server state and manages favorite posts as client state.
📋 What You'll Learn
Fetch blog posts data from a server using getServerSideProps
Store the fetched posts in a prop called posts
Create a client state variable called favorites to track favorite post IDs
Add a button to toggle favorite status for each post
Render the list of posts with favorite buttons reflecting client state
💡 Why This Matters
🌍 Real World
Many web apps need to show data fetched from servers but also let users interact locally without sending every change back to the server immediately.
💼 Career
Understanding server state vs client state is key for building efficient, user-friendly React and Next.js applications that balance data fetching and user interaction.
Progress0 / 4 steps
1
Setup server state with getServerSideProps
Create an async function called getServerSideProps that returns a props object containing a posts array with these exact objects: { id: 1, title: 'Next.js Basics' } and { id: 2, title: 'React Hooks' }.
NextJS
Need a hint?

Use getServerSideProps to fetch or create data on the server and pass it as props.

2
Add client state for favorites using useState
Inside the default exported component called Blog, create a client state variable called favorites initialized as an empty array using useState.
NextJS
Need a hint?

Use useState to create a client state variable for favorites.

3
Add toggle function to update favorites client state
Inside the Blog component, create a function called toggleFavorite that takes a post id. It should add the id to favorites if not present, or remove it if already present, using setFavorites.
NextJS
Need a hint?

Use includes to check if id is in favorites. Use filter to remove it or spread syntax to add it.

4
Render posts with favorite toggle buttons
Inside the Blog component, return a <main> element containing a list of posts. For each post, render its title and a <button> that calls toggleFavorite(post.id) on click. The button text should be 'Unfavorite' if the post id is in favorites, otherwise 'Favorite'.
NextJS
Need a hint?

Use map to loop over posts and render each with a button that toggles favorite status.