Q1. What is useState in React?
- useState is a React Hook that allows us to create and manage state (data) inside a functional component.
const [count, setCount] = useState(0);
Here:
count – current state value.
setCount – function to update the state.
0 – initial value.
Q2. Why do we use useState?
- We use useState to store and update data in a component. When the state changes, React automatically re-renders the component and updates the UI.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<h2>{count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</>
);
}
export default Counter;
When we click the button, the count increases and the UI updates.
Q3. What is the difference between normal variables and useState?
- Normal variables do not trigger a re-render when their values change, but useState updates the component UI when its state changes. Normal variable:
function App() {
let count = 0;
return (
<>
<h2>{count}</h2>
<button onClick={() => count++}>
Increase
</button>
</>
);
}
The UI will not update when you click the button.
Using useState:
function App() {
const [count, setCount] = useState(0);
return (
<>
<h2>{count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</>
);
}
Now the UI updates automatically.
Top comments (0)