State and Event HandlingLesson 2.1
useState hook explained with practical examples
useState syntax, state initialization, state variable, setter function, re-render on state change, functional updates, state with different data types
Managing State with useState
State is data that changes over time and causes the UI to update. useState is the hook that adds state to functional components.
Basic Syntax
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // initial value = 0
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
<button onClick={() => setCount(count - 1)}>-</button>
</div>
);
}useState returns a tuple: the current state value and a setter function. Calling the setter triggers a re-render with the new value.
Functional Updates
When new state depends on old state, use the functional form to avoid stale closure bugs:
// Unsafe โ count may be stale
setCount(count + 1);
// Safe โ always uses latest state
setCount(prev => prev + 1);State With Objects
const [user, setUser] = useState({ name: 'Raj', age: 25 });
// Always spread โ never mutate directly
setUser(prev => ({ ...prev, age: 26 }));Never mutate state directly (state.value = x). React won't detect the change and won't re-render. Always call the setter with a new value or new object.
