Part 6: Reactive State with useState: Anatomy of Reactivity
While props allow a component to receive data from above, State is a component's personal, localized memory. When state changes, React schedules a re-render to update the user interface automatically.
1. Introducing useState
import { useState } from 'react';
export default function LightSwitch() {
const [isOn, setIsOn] = useState(false);
return (
<div className={`p-6 text-center ${isOn ? 'bg-yellow-100' : 'bg-gray-800 text-white'}`}>
<h2>The light is {isOn ? 'ON 💡' : 'OFF 🌑'}</h2>
<button
onClick={() => setIsOn(!isOn)}
className="mt-4 px-4 py-2 font-bold bg-blue-500 text-white rounded"
>
Toggle Switch
</button>
</div>
);
}
2. Functional State Updates
When the next state depends on the previous state value, pass an updater function:
// Guaranteed fresh state calculation
function handleTripleIncrement() {
setCount(prevCount => prevCount + 1);
setCount(prevCount => prevCount + 1);
setCount(prevCount => prevCount + 1);
}
3. Updating Objects and Arrays Immutably
Never mutate state directly:
// Object update:
setUser(prevUser => ({
...prevUser,
email: 'newemail@devify.com'
}));
// Array update (add):
setItems(prev => [...prev, 'New Item']);
// Array update (delete):
setItems(prev => prev.filter(item => item.id !== targetId));
Key Takeaways
- State is local component memory that triggers re-renders when updated.
- Use
setVal(prev => prev + 1)when the new state depends on previous state. - Always update objects and arrays immutably using the spread operator (
...).
In Part 7, we will explore Event Handling in React: synthetic events, parameters, and form triggers!

