Intermediate 18 min readModule: Module 4: Reactive State & useState Hook
useState & Functional State Updaters
Update component state immutably and use functional updaters (prev => prev + 1) for batched updates.
What You Will Learn in This Lesson
- Declaring state with const [state, setState] = useState(initial)
- Why state updates are asynchronous and batched in React
- Using functional updater callbacks to avoid stale state bugs
Introduction & Core Concept
State represents the dynamic data in a component that can change over time based on user interactions, network responses, or timers.
WHY DOES THIS MATTER IN THE REAL WORLD?
Using functional updaters (setCount(prev => prev + 1)) ensures state updates calculate from the freshest value even during rapid clicks.
Safe Functional State Updates
javascriptjavascript
1234567891011function StepCounter() {const [step, setStep] = React.useState(1);const advanceSteps = () => {// Functional updates prevent stale closuressetStep(prev => prev + 1);setStep(prev => prev + 1);};return <button onClick={advanceSteps}>Step: {step}</button>;}
Line-by-Line Technical Breakdown
1Always create new copies when updating arrays or objects in state.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[JAVASCRIPT]
JAVASCRIPT SOURCE EDITOR
Interactive Live CodeIndustry Best Practices & Professional Standards
- Group related state into a single object or custom hook.
Lesson Summary & Core Takeaways
- useState manages local reactive component memory.