What is useState?
useState is a React Hook that allows functional components to manage state. It returns a state variable and a setter function. When the setter function is called, React re-renders the component with updated state.
Basic Syntax:
const [state, setState] = useState(initialValue);
state β Current value
setState β Function to update the value
initialValue β Starting value
Why Do We Need useState?
React components re-render when state changes.
Without state:
No dynamic UI
No user interaction handling
No form handling
No toggle functionality
State makes your UI interactive.
Example 1: Counter
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
**What Happens Here?**
Initial value is 0
When button is clicked
setCount(count + 1) runs
React updates state
Component re-renders
UI updates automatically
Example 2: Toggle Button
import { useState } from "react";
function Toggle() {
const [isOn, setIsOn] = useState(false);
return (
<div>
<h2>{isOn ? "Light ON π‘" : "Light OFF π"}</h2>
<button onClick={() => setIsOn(!isOn)}>
Toggle
</button>
</div>
);
}
Here:
false β Initial state
Clicking button flips the value
UI updates instantly
This pattern is used in:
Dark mode toggle
Show/Hide password
Dropdown menus
Modal open/close
Top comments (0)