useState
is a Hook that lets you add React state to function components
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
What does calling useState
do? It declares a “state variable”. Our variable is called count
. This is a way to “preserve” some values between the function calls — useState
is a new way to use the exact same capabilities that this.state
provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React.
What do we pass to useState
as an argument? The only argument to the useState()
Hook is the initial state. Unlike with classes, the state doesn’t have to be an object. We can keep a number or a string if that’s all we need. (If we wanted to store two different values in state, we would call useState()
twice.)
What does useState
return? It returns a pair of values: the current state and a function that updates it. This is why we write const [count, setCount] = useState()
. This is similar to this.state.count
and this.setState
in a class, except you get them in a pair.