State Cheat Sheet (React)

Subject: React

πŸ“˜ React State β€” Cheat Sheet

🧩 Conceptβœ… Syntax / ExampleπŸ’‘ Description / Notes
Declare State (Functional)const [count, setCount] = useState(0);Initializes state in a functional component using the useState Hook
Access State{count}Just use the state variable inside JSX
Update StatesetCount(count + 1);Updates the value and triggers re-render
Callback UpdatesetCount(prev => prev + 1);Use this when the new value depends on the previous one
Initial State as Objectconst [user, setUser] = useState({ name: "John", age: 25 });You can store multiple values in a single object
Update Object StatesetUser({ ...user, name: "Raj" });Always use spread operator to preserve other fields
Multiple Statesconst [name, setName] = useState(""); const [age, setAge] = useState(0);Declare multiple independent states instead of one big object
State in Class (legacy)this.state = { count: 0 } (in constructor)Used in class components
Update in Classthis.setState({ count: this.state.count + 1 })Use setState() to update class component state
Async Natureconsole.log(count) after setCount() won't show the new value immediatelyState updates are asynchronous
Trigger Re-renderβœ… Yes, when setState or setCount is calledReact automatically re-renders the component
Don't Modify Directly❌ count++ or user.name = "New"Direct modification won’t trigger re-render and breaks best practice