OnlineCBT Logo OnlineCBT
React Tutorial
REACT · LESSON 4

State Management with useState Hook

By Ratan Updated: 16 Oct 2026

Manage dynamic component state, re-renders, and user interactions using the useState hook.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

1. What is Component State?

While props are passed into a component from the outside, state represents data that is created, held, and modified inside the component over time. Whenever state updates, React automatically schedules a re-render to reflect the new data in the browser UI.

2. The useState Hook

Hooks are special functions that allow you to "hook into" React features without writing class components. The useState hook declares a state variable:

import { useState } from 'react';

function Counter() {
  // Syntax: const [stateValue, stateUpdaterFunction] = useState(initialValue);
  const [count, setCount] = useState(0);

  return (
    

Current Question: {count}

); }

3. Functional State Updates

If your new state depends on the previous state value, always pass an updater callback function to setState to avoid stale closure bugs during rapid updates:

// Recommended pattern when computing next state from previous state:
setCount(prevCount => prevCount + 1);

4. Managing Object State

When state is an object, calling the setter replaces the entire object. Use the spread operator (...) to copy existing properties while overriding specific fields:

function UserForm() {
  const [profile, setProfile] = useState({
    name: "Aman",
    role: "Student",
    theme: "light"
  });

  const toggleTheme = () => {
    setProfile(prev => ({
      ...prev,
      theme: prev.theme === "light" ? "dark" : "light"
    }));
  };

  return (
    

Theme: {profile.theme}

); }

5. Managing Array State

Never mutate arrays directly with push() or splice(). Instead, return a new array using the spread operator or filter():

function QuestionBookmarks() {
  const [bookmarks, setBookmarks] = useState([1, 4, 7]);

  // Adding an item immutably
  const addBookmark = (questionNo) => {
    setBookmarks(prev => [...prev, questionNo]);
  };

  // Removing an item immutably
  const removeBookmark = (questionNo) => {
    setBookmarks(prev => prev.filter(q => q !== questionNo));
  };
}

6. Rules of Hooks

  • Only call hooks at the top level: Never call hooks inside loops, conditions, or nested functions.
  • Only call hooks from React function components or custom hooks.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat