PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

React · Theory

useState Example

← All stacks

Theory

84/94

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.

Diagram
useState(false)
      │ click
      ▼
  setLiked(true)
      │
      ▼
   Like → Liked
Exam tip

Click timeline + stale setCount trap.

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.

Short notes

  • Flowclick → setter → next paint.
  • Traplog count immediately after setCount.
  • Fix : c => c + 1 for chained updates.

Questions

1

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

Previous← Vue vs ReactNextClass Components in React →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.