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,β¦