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 State | setCount(count + 1); | Updates the value and triggers re-render |
Callback Update | setCount(prev => prev + 1); | Use this when the new value depends on the previous one |
Initial State as Object | const [user, setUser] = useState({ name: "John", age: 25 }); | You can store multiple values in a single object |
Update Object State | setUser({ ...user, name: "Raj" }); | Always use spread operator to preserve other fields |
Multiple States | const [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 Class | this.setState({ count: this.state.count + 1 }) | Use setState() to update class component state |
Async Nature | console.log(count) after setCount() won't show the new value immediately | State updates are asynchronous |
Trigger Re-render | β
Yes, when setState or setCount is called | React 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 |
Advertisement Slot 1
Advertisement Slot 2