0
0
NextJSframework~30 mins

Optimistic state updates in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Optimistic State Updates in Next.js
📖 Scenario: You are building a simple task list app where users can add tasks quickly. To make the app feel fast, you want to show the new task immediately when the user adds it, even before the server confirms it is saved. This technique is called optimistic state update.
🎯 Goal: Build a Next.js component that shows a list of tasks and lets the user add a new task. The new task should appear instantly in the list before the server responds.
📋 What You'll Learn
Create a React state variable to hold the list of tasks
Create a state variable to hold the new task text
Add a function to handle adding a new task with optimistic update
Render the list of tasks and an input with a button to add tasks
💡 Why This Matters
🌍 Real World
Optimistic updates make apps feel faster by showing changes immediately without waiting for the server. This improves user experience in chat apps, social media, and task managers.
💼 Career
Many modern web apps use optimistic UI updates. Knowing how to implement this pattern is valuable for frontend developers working with React and Next.js.
Progress0 / 4 steps
1
Set up initial tasks state
Create a React functional component called TaskList. Inside it, create a state variable called tasks initialized with an array containing these strings: 'Buy milk' and 'Walk dog'.
NextJS
Need a hint?

Use useState to create tasks with the given initial array.

2
Add new task input state
Inside the TaskList component, create another state variable called newTask initialized as an empty string ''.
NextJS
Need a hint?

Create newTask state to hold the text typed by the user.

3
Add optimistic update function
Inside TaskList, write a function called addTask that does these steps: 1) Immediately add newTask to the tasks array using setTasks. 2) Clear newTask to an empty string. 3) Simulate a server call with setTimeout that waits 1 second and then logs 'Task saved'.
NextJS
Need a hint?

Use setTasks to add the new task right away, then clear the input, then simulate saving with setTimeout.

4
Render tasks and input with button
Complete the TaskList component by returning JSX that shows: 1) An unordered list <ul> with each task in tasks as a list item <li>. 2) An input box with value bound to newTask and an onChange handler to update newTask. 3) A button labeled Add Task that calls addTask when clicked.
NextJS
Need a hint?

Use map to show tasks, bind input value and onChange, and add a button with onClick.