What is useState in React? Explained with Practical Examples
Source: Dev.to
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 the 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 (
## Count: {count}
setCount(count + 1)}>Increment
);
}
export default Counter;
What Happens Here?
- Initial value is
0. - When the button is clicked,
setCount(count + 1)runs. - React updates the state.
- The component re‑renders.
- The UI updates automatically.
Example 2: Toggle Button
import { useState } from "react";
function Toggle() {
const [isOn, setIsOn] = useState(false);
return (
## {isOn ? "Light ON 💡" : "Light OFF 🌙"}
setIsOn(!isOn)}>Toggle
);
}
false→ Initial state.- Clicking the button flips the value.
- UI updates instantly.
Common Uses
- Dark mode toggle
- Show/Hide password
- Dropdown menus
- Modal open/close