The useState hook lets you add state to functional components.
useState returns a stateful value and a function to update it.
import { useState } from 'react';
function Counter() {
// Declare a state variable named "count" with initial value 0
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}When using objects with useState, you need to spread the previous state.
import { useState } from 'react';
function UserForm() {
const [user, setUser] = useState({
name: '',
email: ''
});
const handleNameChange = (e) => {
// Spread the previous state and update only the name property
setUser({ ...user, name: e.target.value });
};
const handleEmailChange = (e) => {
setUser({ ...user, email: e.target.value });
};
return (
<form>
<input
value={user.name}
onChange={handleNameChange}
placeholder="Name"
/>
<input
value={user.email}
onChange={handleEmailChange}
placeholder="Email"
/>
</form>
);
}If the new state depends on the previous state, use the functional update form.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
// This is safer for concurrent updates
const increment = () => {
setCount(prevCount => prevCount + 1);
};
return (
<button onClick={increment}>
Increment
</button>
);
}If the initial state is expensive to compute, provide a function instead.
import { useState } from 'react';
function ExpensiveInitialState() {
// The function is only called during the first render
const [state, setState] = useState(() => {
const initialState = someExpensiveComputation();
return initialState;
});
return (
// Component JSX
);
}