Hook: useState
Master the useState Hook, the official React function that lets you add state variables to your functional components.
Learning Goals
The Core Concept
The useState hook is a built-in React function that lets you add local state to a functional component. It is the most common hook in React development.
When you call useState(initialValue), it returns an array containing exactly two items: first, the current state value, and second, a function to update that state value. We use JavaScript array destructuring to assign names to both items in a single line (typically using the pattern [value, setValue]). It is critical to always use the setter function to update the state, rather than mutating the variable directly.
Visual guide
React hooks data flow
A simple original diagram to connect the lesson idea with real project flow.
Code & Implementation
import { useState } from 'react';
export default function Counter() {
// Declare count state variable, starting at 0
const [count, setCount] = useState(0);
return (
<div style={{ padding: '20px', textAlign: 'center' }}>
<h2>Interactive Counter</h2>
<p>Current count: {count}</p>
{/* Update state using the setter function */}
<button onClick={() => setCount(count + 1)} style={{ marginRight: '8px' }}>
Increment
</button>
<button onClick={() => setCount(0)}>
Reset
</button>
</div>
);
}Expected Output
UI preview: - Heading 'Interactive Counter' - Text 'Current count: 0' - Buttons 'Increment' and 'Reset'
Dark Mode Toggle
Hands-on practice task
The Challenge
Build a React component that manages a boolean dark mode state. When the user clicks a button, toggle the state and change the background and text color of the component.
Helpful Hints
- •Initialize const [darkMode, setDarkMode] = useState(false);.
- •Toggle it with setDarkMode(!darkMode) inside the onClick handler.
- •Set styles dynamically based on the darkMode boolean.
Quick Knowledge Check
Why does React use hooks instead of regular functions?
What happens if I call count = count + 1 directly?
Continue Learning
Next steps after this lesson
Build a React component that manages a boolean dark mode state. When the user clicks a button, toggle the state and change the background and text color of the component.
Supercharge your career workflows!
Discover free online utilities to format data, build job applications, and automate your productivity routine with TechIdea.