Topic 15 of 54
Component State
Overview
Props are read-only and passed down from parents. But what if a component needs to change its own data over time based on user interaction (like tracking if a modal is open, or keeping score in a game)? This is where 'State' comes in. State is the 'memory' of a component. When a component's state changes, React automatically re-renders that specific component to update the UI.
Syntax
Local variables don't trigger a re-render. Even if the variable changes in memory, React has no idea it needs to update the screen. You must use React State.
The problem with normal variables
jsx
// ❌ THIS WILL NOT WORK!
function BrokenCounter() {
let count = 0;
const increment = () => {
count += 1; // The variable updates, but React doesn't care!
console.log(count); // Will print 1, 2, 3... but UI remains 0
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Add</button>
</div>
);
}Common Pitfalls
- Assuming a standard `let` variable will update the screen.
- Trying to use state for data that can simply be calculated from existing props (derived data).
Interview Tips
- State vs Props is a guaranteed interview question. Props = Immutable arguments passed from above. State = Mutable memory managed locally by the component itself.
Real-World Example
Toggling a dark mode theme.
example
jsx
// You need state to remember if dark mode is currently active
// When it toggles, React automatically re-renders the component to apply the new class
function ThemeWrapper() {
const [isDark, setIsDark] = useState(false);
return (
<div className={isDark ? 'theme-dark' : 'theme-light'}>
<button onClick={() => setIsDark(!isDark)}>
Toggle Theme
</button>
</div>
);
}