Bird
Raised Fist0
NextJSframework~10 mins

Optimistic updates pattern in NextJS - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Optimistic updates pattern
User triggers update
Update UI immediately
Send update request to server
Server responds
Keep UI
This flow shows how the UI updates right away when the user acts, then waits for the server response to confirm or undo the change.
Execution Sample
NextJS
const [items, setItems] = useState(['apple', 'banana']);

async function addItem(newItem) {
  const oldItems = items;
  setItems([...items, newItem]);
  try {
    await fetch('/api/add', { method: 'POST', body: JSON.stringify({ item: newItem }) });
  } catch {
    setItems(oldItems); // revert on failure
  }
}
This code adds an item to the list immediately, then tries to save it on the server. If saving fails, it reverts the list.
Execution Table
StepActionUI State (items)Server RequestServer ResponseResulting UI State
1User clicks add 'orange'['apple', 'banana']NoNo['apple', 'banana']
2UI updates immediately['apple', 'banana', 'orange']NoNo['apple', 'banana', 'orange']
3Send POST request to /api/add['apple', 'banana', 'orange']POST /api/add {item: 'orange'}Pending['apple', 'banana', 'orange']
4Server responds success['apple', 'banana', 'orange']POST /api/add {item: 'orange'}Success['apple', 'banana', 'orange']
5No UI change needed['apple', 'banana', 'orange']NoNo['apple', 'banana', 'orange']
6User clicks add 'grape'['apple', 'banana', 'orange']NoNo['apple', 'banana', 'orange']
7UI updates immediately['apple', 'banana', 'orange', 'grape']NoNo['apple', 'banana', 'orange', 'grape']
8Send POST request to /api/add['apple', 'banana', 'orange', 'grape']POST /api/add {item: 'grape'}Pending['apple', 'banana', 'orange', 'grape']
9Server responds failure['apple', 'banana', 'orange', 'grape']POST /api/add {item: 'grape'}Failure['apple', 'banana', 'orange']
10UI reverts to old state['apple', 'banana', 'orange']NoNo['apple', 'banana', 'orange']
💡 Execution stops after server response and UI state is confirmed or reverted.
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 7After Step 9Final
items['apple', 'banana']['apple', 'banana', 'orange']['apple', 'banana', 'orange']['apple', 'banana', 'orange', 'grape']['apple', 'banana', 'orange']['apple', 'banana', 'orange']
Key Moments - 3 Insights
Why does the UI update before the server confirms the change?
The UI updates immediately to give instant feedback to the user, as shown in steps 2 and 7 of the execution_table. This is the core of optimistic updates.
What happens if the server rejects the update?
If the server responds with failure (step 9), the UI reverts to the previous state (step 10), undoing the optimistic change.
Why do we keep a copy of the old state?
We keep the old state to revert the UI if the server rejects the update, as seen in the catch block in the code and steps 9-10 in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4. What is the UI state after the server responds successfully?
A['apple', 'banana', 'orange']
B['apple', 'banana']
C['apple', 'banana', 'orange', 'grape']
D[]
💡 Hint
Check the 'Resulting UI State' column at step 4 in the execution_table.
At which step does the UI revert to the old state after a failed server response?
AStep 9
BStep 10
CStep 7
DStep 5
💡 Hint
Look for the step where the 'Resulting UI State' changes back to the previous list in the execution_table.
If the server always succeeds, how would the variable_tracker change?
AThe 'items' variable would revert after each update.
BThe 'items' variable would stay the same as start.
CThe 'items' variable would never revert and keep growing.
DThe 'items' variable would be empty.
💡 Hint
Check how 'items' changes after successful and failed responses in variable_tracker.
Concept Snapshot
Optimistic updates pattern:
- Update UI immediately on user action
- Send server request in background
- If server succeeds, keep UI as is
- If server fails, revert UI to old state
- Improves user experience by reducing wait time
Full Transcript
The optimistic updates pattern lets the UI change right away when a user acts, without waiting for the server. This makes the app feel faster and more responsive. The code first updates the UI state, then sends a request to the server. If the server confirms success, the UI stays the same. If the server fails, the UI reverts to the previous state. This pattern requires keeping a copy of the old state to revert if needed. The execution table shows each step: user action, UI update, server request, server response, and final UI state. The variable tracker follows the list of items as it changes. Key moments include understanding why the UI updates before server confirmation and how failures are handled. The visual quiz tests understanding of these steps. This pattern is common in Next.js apps to improve user experience.

Practice

(1/5)
1. What is the main idea behind the optimistic updates pattern in Next.js?
easy
A. Update the UI immediately before server confirmation to improve user experience
B. Wait for server response before updating the UI to ensure accuracy
C. Reload the entire page after every data change to keep UI fresh
D. Disable user input until the server confirms the update

Solution

  1. Step 1: Understand the purpose of optimistic updates

    Optimistic updates aim to make the app feel faster by showing changes immediately.
  2. Step 2: Compare UI update timing

    Instead of waiting for the server, the UI updates first, then confirms or reverts based on server response.
  3. Final Answer:

    Update the UI immediately before server confirmation to improve user experience -> Option A
  4. Quick Check:

    Optimistic updates = Immediate UI update [OK]
Hint: UI updates first, server confirms later [OK]
Common Mistakes:
  • Waiting for server before UI update
  • Reloading entire page unnecessarily
  • Disabling user input during update
2. Which of the following is the correct way to implement an optimistic update in Next.js using React hooks?
easy
A. Use useEffect to update state only after server confirms
B. Send API request first, then call setState after response
C. Call setState to update UI, then send API request, revert on error
D. Reload the page after API call to update UI

Solution

  1. Step 1: Identify optimistic update flow

    Optimistic update means updating UI state immediately with setState.
  2. Step 2: Confirm API call and handle errors

    Send API request after UI update, and revert state if the request fails.
  3. Final Answer:

    Call setState to update UI, then send API request, revert on error -> Option C
  4. Quick Check:

    Update state first, then API call [OK]
Hint: Update state first, then call API [OK]
Common Mistakes:
  • Waiting for API before updating state
  • Using useEffect incorrectly for optimistic update
  • Reloading page instead of updating state
3. Consider this Next.js React component snippet using optimistic updates:
const [likes, setLikes] = useState(0);

async function handleLike() {
  setLikes(likes + 1);
  try {
    await fetch('/api/like', { method: 'POST' });
  } catch {
    setLikes(likes); // revert on error
  }
}

What will the UI show if the API call fails?
medium
A. The likes count stays incremented by 1
B. The likes count increments by 2
C. The likes count resets to zero
D. The likes count reverts to the original value

Solution

  1. Step 1: Analyze optimistic update behavior

    The UI increments likes immediately by 1 using setLikes(likes + 1).
  2. Step 2: Check error handling

    If the API call fails, setLikes(likes) resets likes to the original value before increment.
  3. Final Answer:

    The likes count reverts to the original value -> Option D
  4. Quick Check:

    API error triggers revert to old likes [OK]
Hint: Revert state on API failure [OK]
Common Mistakes:
  • Assuming UI stays incremented after failure
  • Resetting likes to zero incorrectly
  • Incrementing likes twice by mistake
4. You wrote this optimistic update code in Next.js but the UI never reverts on API failure:
const [count, setCount] = useState(0);

async function increment() {
  setCount(count + 1);
  try {
    await fetch('/api/increment', { method: 'POST' });
  } catch {
    setCount(count - 1);
  }
}

What is the bug causing the revert to fail?
medium
A. Using stale count value inside catch block
B. Not awaiting the setCount call
C. Missing return statement after setCount
D. API call method should be GET, not POST

Solution

  1. Step 1: Understand state closure issue

    The count variable inside catch is the old value before increment.
  2. Step 2: Explain why revert fails

    Subtracting 1 from stale count does not revert to original because count was already incremented in UI.
  3. Final Answer:

    Using stale count value inside catch block -> Option A
  4. Quick Check:

    State closure causes revert failure [OK]
Hint: Avoid stale state in async error handlers [OK]
Common Mistakes:
  • Expecting setState to be async
  • Ignoring stale closure of state variable
  • Wrong HTTP method for API call
5. You want to implement optimistic updates for a comment submission in Next.js. Which approach best handles UI update, server confirmation, and error rollback?
hard
A. Reload the page after comment submission to show new comment
B. Add comment to UI state immediately, send API request, remove comment if API fails
C. Add comment to UI state only after API confirms success
D. Send API request first, then add comment to UI state after success

Solution

  1. Step 1: Apply optimistic update pattern

    Update UI immediately by adding comment to state to improve responsiveness.
  2. Step 2: Handle server confirmation and errors

    Send API request; if it fails, remove the comment from UI to keep data consistent.
  3. Final Answer:

    Add comment to UI state immediately, send API request, remove comment if API fails -> Option B
  4. Quick Check:

    UI update first, revert on error [OK]
Hint: Add UI item first, remove on failure [OK]
Common Mistakes:
  • Waiting for API before UI update
  • Adding comment only after success
  • Reloading page instead of updating state