useState is a React Hook used to store and update data in a component.
For example:
- Counter value
- Username
- Login status
- Shopping cart items.
- Basic syntax:
const [state, setState] = useState(initialValue);
- state — current value.
- setState — function to update the value.
- useState(initialValue) — sets the starting value.
- Example: Counter app:
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
return (
Count: {count}
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default App;
How it works:
- useState(0) sets the initial count to 0.
- count stores the current number.
- When you click Increase, setCount(count + 1) updates the number.
React re-renders the component to show the new value.
Example:
Change a name
import { useState } from "react";
function App() {
const [name, setName] = useState("Sathish");
return (
Hello, {name}!
setName("Kumar")}>
Change Name
);
}
export default App;
Before clicking: Hello, Sathish!
After clicking: Hello, Kumar!
- Important points:
- Import useState from React.
- Call it at the top level of your component.
- Don't directly modify the state variable. Use its setter function.
- useState can store numbers, strings, booleans, arrays, and objects.
Top comments (0)