Home

useState

useState is a Hook in React that lets function components add stateful logic. It is imported from the React library and is used only within functional components or custom hooks. When called, useState returns a pair: the current state value and a function to update that value. You can use array destructuring to assign them: [state, setState]. You may call useState multiple times in a single component to manage independent pieces of state.

The initial state can be a value, such as 0, or a function that returns the initial

In contrast to class components, state in functional components with useState is isolated per hook call. Rules

value.
The
function
form
is
useful
for
expensive
computations,
as
it
runs
only
on
the
initial
render.
Calling
the
setter
with
a
new
value
schedules
a
re-render
of
the
component.
State
updates
are
asynchronous
and
may
be
batched
with
other
updates
for
performance.
If
the
new
state
depends
on
the
previous
state,
you
can
pass
a
function
to
the
setter:
setState(prev
=>
prev
+
1).
Note
that
useState
does
not
automatically
merge
updates
into
objects;
if
you
store
an
object,
you
must
spread
the
previous
state
yourself,
e.g.,
setState(prev
=>
({
...prev,
...Updates
})).
of
hooks
apply:
only
call
hooks
at
the
top
level
and
only
from
React
function
components
or
custom
hooks,
and
in
the
same
order
on
every
render.
useState
is
widely
used
for
interactive
UI,
such
as
counters,
form
inputs,
toggles,
and
conditional
rendering.