Hooks useState
Last updated
Last updated
Using the useState()
API, you can create a new state variable, and have a way to alter it. useState()
accepts the initial value of the state item and returns an array containing the state variable, and the function you call to alter the state. Since it returns an array we use array destructuring to access each individual item, like this: const [count, setCount] = useState(0)
Here’s a practical example:
You can add as many useState()
calls you want, to create as many state variables as you want. Just make sure you call it in the top level of a component (not in an if
or in any other block).
Example on Codepen: