What Is useState?
useState is a React Hook that allows us to add and manage state in a functional component.
In simple words, useState helps us store a value and update it when needed.
For example, we can use state to store:
- A counter value
- User input
- A selected product
- A login status
- Data from an API
How to Import useState
First, we need to import it from React.
import { useState } from "react";
Basic Syntax
const [state, setState] = useState(initialValue);
Here:
-
state→ stores the current value. -
setState→ updates the value. -
initialValue→ the starting value.
Simple Counter Example
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
}
return (
<div>
<h1>{count}</h1>
<button onClick={increment}>Increase</button>
</div>
);
}
export default Counter;
When the button is clicked:
- The
increment()function runs. -
setCount(count + 1)updates the state. - React re-renders the component.
- The updated value appears on the screen.
Another Example: Updating Text
import { useState } from "react";
function App() {
const [name, setName] = useState("");
return (
<div>
<input
type="text"
onChange={(event) => setName(event.target.value)}
/>
<h2>Hello, {name}</h2>
</div>
);
}
export default App;
As the user types in the input field, the name state is updated and displayed on the screen.
Top comments (0)