Components often need to change what’s on the screen as a result of an interaction. Typing into the form should update the input field, clicking “next” on an image carousel should change which image is displayed, clicking “buy” should put a product in the shopping cart. Components need to “remember” things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called state.
First, take an example of a constant variable usage in a component
funcion CountBTN() {
const count = 0;
function handler() {
count = count + 1;
}
return (
<button onClick={handler}>{count}</button>
);
}
When you click on that button, the counter does not update. The handler is updating the local variable, but two things prevent that change from being visible.
To update a component with new data, two things need to happen:
The useState Hook provides those two things:
Now with the state, clicking the count button, it will increase.
funcion CountBTN() {
const [count, setCount] = useState();
function handler() {
setCount(count => count + 1);
}
return (
<button onClick={handler}>{count}</button>
);
}
Every time your component renders, useState gives you an array containing two values: