State in React

📘 React.js 👁 46 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

State is used to store and manage data that changes over time in a React component. When state changes, React automatically re-renders the component to reflect the updated data.


What is State?

  • State is local to a component

  • It can change based on user interaction or logic

  • Updating state causes the UI to update


Using State with useState

In functional components, state is managed using the useState hook.

import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); }
  • count → current state value

  • setCount → function to update state

  • 0 → initial state value


Updating State

Correct Way

setCount(count + 1);

Using Previous State

setCount(prevCount => prevCount + 1);

This is recommended when the new state depends on the old state.


State with Multiple Values

const [user, setUser] = useState({ name: "Alice", age: 22 });

Update part of the state:

setUser({ ...user, age: 23 });

State vs Props

StateProps
Managed inside componentPassed from parent
Can changeRead-only
Triggers re-renderDoes not change itself

Common Use Cases for State

  • Form inputs

  • Toggle buttons

  • Counters

  • Modal visibility

  • API data storage


Important Rules of State

  • ❌ Do not modify state directly

count = count + 1; // wrong
  • ✅ Always use the setter function

setCount(count + 1);
  • State updates may be asynchronous


Example: Toggle State

function Toggle() { const [isOn, setIsOn] = useState(false); return ( <button onClick={() => setIsOn(!isOn)}> {isOn ? "ON" : "OFF"} </button> ); }

Key Points

  • State holds dynamic data

  • useState is the most common hook

  • Updating state re-renders the component

  • Use previous state when needed


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes