The useState hook allows function components to manage state. Unlike props, which are passed to a component, state variables are internal to a component and cause re-renders when updated.
After reading this article, you should be able to:
The useState hook returns an array with two values:
import { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
return (
Count: {count}
);
}
Setter functions update state values, but the update takes effect on the next render.
function App() {
const [count, setCount] = useState(0);
if (count === 0) setCount(1);
console.log(count);
return Count: {count}
;
}
The console will show:
0
1
To ensure state updates happen sequentially, use an updater function:
function App() {
const [count, setCount] = useState(0);
if (count === 0) {
setCount(prevCount => prevCount + 1);
setCount(prevCount => prevCount + 1);
setCount(prevCount => prevCount + 1);
}
return Count: {count}
;
}
Now, the rendered output will be:
Count: 3
The useState hook is commonly used for managing form inputs:
function FormWithHooks() {
const [inputValue, setInputValue] = useState('');
return (
);
}
This pattern keeps the input field and state synchronized, making the input a controlled input.
In this reading, you learned:
useState to manage state in function components.useState to create controlled inputs in a form.To learn more, visit:
The useState hook is fundamental in React applications, allowing components to maintain internal state and respond to user interactions.