useState Example — React Technical Interview Questions & Answers

useState Example

useState Example

  • Walk it like a teacher, not a definition. Counter starts at 0. User clicks. You call setCount(c => c + 1). React schedules render two. Button text becomes 1. Second click → 2. If you logged count right after setCount, you still see the old number — updates are async to the next paint. That surprise is the viva trap.
  • Same hook, different story from the ‘what is’ page: here you narrate the click timeline. Mention the stale closure if someone writes setCount(count + 1) twice in one handler — both see 0, result is 1. Functional updater fixes it.
  • useState Example — on screen: Clicked 0 → 1 → 2. Functional updater c => c+1 is safer if clicks are fast.
  useState(false)
      │ click
      ▼
  setLiked(true)
      │
      ▼
   Like → Liked

Technical Interview Tip: Click timeline + stale setCount trap.

Code Examples for useState Example

Example

// useState click walkthrough
import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount((c) => c + 1)}>
      Clicked {count}
    </button>
  );
}

useState Example — on screen: Clicked 0 → 1 → 2. Functional updater c => c+1 is safer if clicks are fast.

How to Explain useState Example to an Interviewer

Why can two setCount(count + 1) in one click only add 1?

Both read the same count