Category: react
what is useState
Published on 23 Oct 2026
Explanation
useState is a React Hook that
allows functional components to store and
manage state. State represents data that
can change over time, such as
a counter value, username, or form
input. When the state changes, React
re-renders the component to display the
updated value.
Code:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return <h2>Count: {count}</h2>;
}
export default Counter;
Explanation
The useState Hook returns an array
containing the current state value and
a setter function. Call the setter
function to request a state update.
React then renders the component with
the updated state.
Code:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
Explanation
When the next state depends on
the previous state, use the functional
updater form. React passes the previous
state value to the updater. This
is especially useful when multiple updates
are queued together.
Code:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function increment() {
setCount(previousCount => previousCount + 1);
}
return <button onClick={increment}>Count: {count}</button>;
}
Explanation
useState can store the value entered
into an input field. By connecting
the input's value and onChange handler
to state, you create a controlled
component. The displayed input value stays
synchronized with React state.
Code:
import { useState } from 'react';
function UsernameForm() {
const [username, setUsername] = useState('');
return (
<div>
<input
value={username}
onChange={event => setUsername(event.target.value)}
/>
<p>Username: {username}</p>
</div>
);
}
Explanation
Call useState at the top level
of a React component or custom
Hook, not inside loops, conditions, or
nested functions. Do not modify state
variables directly. Instead, use the setter
function. React may batch updates, so
use a functional updater when the
next value depends on the previous
value.
Code:
const [user, setUser] = useState({ name: 'Arun' });
// Correct: create a new object
setUser(previousUser => ({
...previousUser,
name: 'Kumar'
}));
// Incorrect: mutates the existing object
// user.name = 'Kumar';