useState Hook Demo

What is useState?

useState is a React Hook that lets you add state to functional components. It returns an array with two elements: the current state value and a function to update it.

Basic Syntax:

const [state, setState] = useState(initialValue);

// Examples:
const [count, setCount] = useState(0);
const [name, setName] = useState('John');
const [items, setItems] = useState([]);
const [user, setUser] = useState({ name: 'Alice', age: 30 });

Counter Example

0

✅ Uses functional update: setCount(prev => prev + 1)

Toggle Switch Example

Status: Disabled

✅ Uses functional update: setIsToggled(prev => !prev)

Array State Updates

Item 1
Item 2
⚠️ Common Gotcha: Don't mutate arrays directly!
❌ items.push(newItem)
✅ setItems(prev => [...prev, newItem])

Object State Updates

Name: John

Age: 25

⚠️ Common Gotcha: Don't mutate objects directly!
❌ user.name = newName
✅ setUser(prev => ({ ...prev, name: newName }))

Edge Cases & Best Practices

🔄 Functional Updates: Use when new state depends on previous state
setCount(prev => prev + 1) vs setCount(count + 1)

Why functional updates? They ensure you're working with the latest state value, especially important in async operations, event handlers, and when multiple updates happen quickly. The functional approach prevents stale closures.

🔒 Immutable Updates: Always create new objects/arrays
Arrays: [...prev, newItem] | Objects: { ...prev, newProp: value }

Why immutability? React uses Object.is() comparison to detect state changes. If you mutate the original object/array, React won't detect the change and won't re-render. Always create new references for updates.

🕒 Stale Closure: A common pitfall in async operations
setTimeout(() => setCount(prev => prev + 1), 1000)

The problem: In closures (like setTimeout, useEffect), the count variable captures the value from when the closure was created, not the current value. Using functional updatesprev => prev + 1 ensures you get the latest state.

📦 Batch Updates: React optimizes performance by batching updates
Multiple setState calls in one handler = one re-render

How it works: React automatically batches multiple state updates in event handlers into a single re-render for better performance. In React 18+, this batching also happens in promises, timeouts, and other async operations (Automatic Batching).

⚡ State Updates are Asynchronous: setState doesn't immediately update the state
setCount(count + 1); console.log(count); // Still old value!

Remember: State updates are scheduled and happen after the current execution. If you need to perform actions after state updates, use useEffect or access the new state in the next render cycle.