The useState Hook is one of the most commonly used Hooks in React. It allows functional components to store and update data that can change while the application is running.
useState is a React Hook that allows a functional
component to create and manage state.
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
return (
<h1>
{count}
</h1>
);
}
State is data that belongs to a component and can change over time.
Examples of state include:
Before using useState, import it from React.
import { useState } from "react";
This makes the Hook available inside the component.
The basic syntax is:
const [state, setState] = useState(initialValue);
There are three important parts:
state — current state value.setState — function used to update the state.initialValue — starting value.const [count, setCount] = useState(0);
Here:
count contains the current value.setCount updates the value.0 is the initial value.The setter function is used to update state.
const [count, setCount] = useState(0);
function increase() {
setCount(count + 1);
}
Calling setCount() requests an update to the state.
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>
{count}
</h1>
<button
onClick={() =>
setCount(count + 1)
}
>
Increase
</button>
</div>
);
}
export default App;
The value passed to useState() becomes the initial state.
const [name, setName] = useState("Rahul");
const [age, setAge] = useState(20);
const [isLoggedIn, setIsLoggedIn] =
useState(false);
State can store string values.
const [name, setName] = useState("");
function changeName() {
setName("Rahul");
}
The state can then be displayed using JSX.
<h2>
{name}
</h2>
Numbers can also be stored in state.
const [age, setAge] = useState(18);
function increaseAge() {
setAge(age + 1);
}
Boolean state is useful for values such as visible/hidden, logged in/logged out, or enabled/disabled.
const [isVisible, setIsVisible] =
useState(true);
function toggle() {
setIsVisible(!isVisible);
}
import { useState } from "react";
function App() {
const [visible, setVisible] = useState(true);
return (
<div>
<button
onClick={() =>
setVisible(!visible)
}
>
Toggle
</button>
{visible && (
<p>
This text is visible.
</p>
)}
</div>
);
}
An array can also be stored in state.
const [courses, setCourses] = useState([
"HTML",
"CSS",
"React"
]);
The array can be displayed using map().
{courses.map(course => (
<li key={course}>
{course}
</li>
))}
A new array can be created using the spread operator.
setCourses([
...courses,
"JavaScript"
]);
This creates a new array containing the existing courses and the new course.
Objects can be stored in state.
const [student, setStudent] = useState({
name: "Rahul",
age: 20,
course: "React"
});
Object state is useful for related values.
When updating an object, preserve the existing properties that you want to keep.
setStudent({
...student,
age: 21
});
The spread operator copies the existing properties and the new
age value replaces the old one.
The useState Hook is commonly used to control form
inputs.
const [name, setName] = useState("");
<input
value={name}
onChange={(e) =>
setName(e.target.value)
}
/>
When state is updated, React schedules the component to render again so the interface can reflect the new state.
const [count, setCount] = useState(0);
setCount(count + 1);
The updated value can then appear in the rendered interface.
State should be updated through its setter function instead of directly modifying the state variable.
Avoid:
count = count + 1;
Prefer:
setCount(count + 1);
When the new state depends on the previous state, a function can be passed to the setter.
setCount(previousCount =>
previousCount + 1
);
This form clearly expresses that the new value depends on the previous value.
A component can use multiple useState Hooks.
const [name, setName] = useState("");
const [age, setAge] = useState(18);
const [isStudent, setIsStudent] =
useState(true);
Each state variable has its own setter function.
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
function increase() {
setCount(count + 1);
}
function decrease() {
setCount(count - 1);
}
return (
<div>
<h1>
{count}
</h1>
<button onClick={increase}>
+
</button>
<button onClick={decrease}>
-
</button>
</div>
);
}
export default App;
The setter function can also be used to return state to its initial value.
const [count, setCount] = useState(0);
function reset() {
setCount(0);
}
Boolean state can control whether an element is displayed.
const [loggedIn, setLoggedIn] =
useState(false);
return (
<div>
{loggedIn ? (
<h2>
Welcome User
</h2>
) : (
<h2>
Please Login
</h2>
)}
</div>
);
State is often changed as a result of user events.
function handleClick() {
setCount(count + 1);
}
<button onClick={handleClick}>
Increase
</button>
The event handler calls the state setter.
If calculating the initial state requires work, a function can be
passed to useState.
const [value, setValue] = useState(() => {
return calculateInitialValue();
});
React can use the function to obtain the initial value.
When multiple updates depend on the previous value, use the updater function form.
setCount(previousCount =>
previousCount + 1
);
setCount(previousCount =>
previousCount + 1
);
This makes each update explicitly depend on the previous state value.
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
const [name, setName] = useState("");
function increase() {
setCount(previousCount =>
previousCount + 1
);
}
function reset() {
setCount(0);
}
return (
<div>
<h1>
Counter: {count}
</h1>
<button onClick={increase}>
Increase
</button>
<button onClick={reset}>
Reset
</button>
<br />
<input
value={name}
onChange={(e) =>
setName(e.target.value)
}
placeholder="Enter name"
/>
<h2>
Hello {name}
</h2>
</div>
);
}
export default App;
useState.Example of direct modification to avoid:
student.age = 21;
Prefer:
setStudent({
...student,
age: 21
});
useState for data that changes over time.useState is a React Hook for managing component state.useState Hooks can be used in one component.
Question: What is the main purpose of the
useState Hook in React?