MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
The useState Hook Fundamentals0%
Study Materials
React.js for BeginnersProgress 0%
1.1Why React and Single-Page Architecture1.2Setting Up Modern React with Vite1.3React Project Directory Structure and Entry Points1.4Virtual DOM and React Render Cycle Explained
4.1Introduction to Component State4.2The useState Hook Fundamentals4.3Updating State and Immutable Updates4.4Lifting State Up Between Siblings
HomeTutorialsReact.js for BeginnersThe useState Hook Fundamentals
Updating State and Immutable Updates

The useState Hook Fundamentals

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

1. Introducing useState

The useState hook is the fundamental tool for introducing local state into a React functional component. It is imported directly from the 'react' package.

1import { useState } from 'react';

2. Anatomy of useState

When you call useState, you pass the initial state value as an argument. It returns an array containing exactly two items:

1const [state, setState] = useState(initialValue);
  1. 1
    The State Variable (state): The current value of the state on this render.
  2. 2
    The Updater Function (setState): A function that updates the state variable and triggers React to re-render the component.

ES6 Array Destructuring

Because useState returns a 2-element array [currentValue, updaterFunction], React developers use ES6 array destructuring to assign custom names:

1// Destructuring the 2-element array
2const [count, setCount] = useState(0);
3const [name, setName] = useState('Rahul');
4const [isOpen, setIsOpen] = useState(false);
5const [items, setItems] = useState([]);

Convention: If the state variable is named foo, the updater function is conventionally named setFoo.

3. A Complete Working Example: Interactive Counter

1import React, { useState } from 'react';
2 
3export default function Counter() {
4 // Declare state variable 'count' initialized to 0
5 const [count, setCount] = useState(0);
6 
7 return (
8 <div className="counter-card">
9 <h2>Interactive Counter</h2>
10 <p className="count-display">Current value: {count}</p>
11
12 <div className="btn-group">
13 <button onClick={() => setCount(count + 1)}>
14 Increment (+)
15 </button>
16 <button onClick={() => setCount(count - 1)}>
17 Decrement (-)
18 </button>
19 <button onClick={() => setCount(0)}>
20 Reset
21 </button>
22 </div>
23 </div>
24 );
25}

4. How useState Works Across Renders

Let's trace what happens when the user clicks "Increment (+)":

  1. 1
    Initial Mount:
  • React executes Counter().
  • useState(0) returns [0, setCount].
  • React renders <p>Current value: 0</p>.
  1. 1
    User Clicks Increment:
  • setCount(0 + 1) is called with value 1.
  • React records the new state for this component instance as 1 and queues a re-render.
  1. 1
    Re-render:
  • React executes Counter() a second time.
  • useState(0) is invoked again, but React remembers that state is now 1! It returns [1, setCount].
  • React renders <p>Current value: 1</p>.
  • React diffs the Virtual DOM and updates the text node in the real DOM from 0 to 1.

5. Lazy Initial State

If your initial state requires an expensive computation (e.g., parsing a large JSON file or reading from localStorage), do not execute the function directly in useState(...) because it will run on every single render:

1// ❌ Inefficient: Reads localStorage on EVERY render
2const [token, setToken] = useState(localStorage.getItem('auth_token'));
3 
4// ✅ Efficient: Lazy initial state function runs ONLY on initial mount
5const [token, setToken] = useState(() => {
6 return localStorage.getItem('auth_token') || '';
7});

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does the useState hook return?
Question 2
What naming convention is universally followed for state updater functions?
Question 3
When does React apply the initial value passed into useState(initialValue)?
Question 4
Why would a developer pass a callback function to useState(() => getInitialData())?
Question 5
What happens if you call setCount(5) when the current count is already 5?
Next Lesson

Updating State and Immutable Updates

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Introduction to Component StateUpdating State and Immutable Updates

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Beginners with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext