useState

Subject: React

πŸ” What is useState?

useState is a Hook in React that lets you add state (i.e., memory/variables) to functional components.

Before Hooks, only class components could hold state using this.state. Now, functional components can hold and update state too β€” thanks to useState.


πŸ“¦ Syntax

PartMeaning
stateVariableCurrent value of the state
setStateFunctionFunction to update that state
useState(value)Initializes state with given initial value

βœ… Example: Counter App

πŸ” What’s Happening:

  • useState(0) initializes count with 0
  • setCount(count + 1) updates the value
  • React re-renders the component with the new count

🧠 Logic Behind the Scenes

React keeps track of count and automatically updates the DOM when setCount() is called.


βœ… Another Example: Input Field (Form)

πŸ” Explanation:

  • name stores the input value
  • setName() updates it when typing
  • React shows: β€œHello, {name}” in real time

πŸ” Important Rules for useState

βœ… RuleπŸ” Why It Matters
Don’t mutate state directlyUse setState() instead of modifying variable
State updates are asyncDon’t expect immediate changes after setting state
Can use multiple useStatesSeparate states for different variables

βœ… Multiple State Variables

Or using an object:


⚠️ Common Mistakes

MistakeFix
count++Use setCount(count + 1)
Forgot to import useStateimport { useState } from 'react'
Modify state object directlyUse spread: { ...oldState, key: v }

🧠 Best Practice: Functional Updates

Use when updating state based on the previous value:

Helps avoid bugs with async updates or inside loops.


πŸ“Œ Summary

FeatureDescription
useState()Initializes state in a functional component
setState functionUpdates the value and triggers re-render
Re-renders UIReact auto-updates DOM when state changes
Use CasesForms, toggles, counters, filters, etc.

πŸ‘‰ Explore more Hooks like useEffect