
what is useState() ?
The React useState Hook allows us to track state in a function component. State generally refers to data or properties that need to be tracking in an application.
What is "state"?
State is data that changes over time (like a counter, form input, or toggle), When state changes, the component re-renders to reflect the new data
Basic Syntax
const [stateVariable, setStateFunction] = useState(initialValue);
- stateVariable: current value of the state
- setStateFunction: function to update the value
- initialValue: starting/default value
Example: Counter App
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // initialize with 0
return (
<>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increase</button>
</>
);
}
When you click the button:
- setCount() updates the value of coun
- The component re-renders with the new count
Example: Input Field (Controlled Component)
function NameForm() {
const [name, setName] = useState('');
return (
<>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<p>Hello, {name}!</p>
</>
);
}
Summary
Concept | Description |
---|---|
useState() | Adds local state to function components |
Updates with | setStateFunction(newValue) |
Triggers | Re-render on state change |
Initial Value | Set in useState(initialValue) |