Hooks are special functions that allow us to use react features. useState is a Hook, that allows you to use state in function components.
This Hook declares a state inside a function component. In a class component, we’d usually use this.state
to work with our state, using useState we use useState()
. In class components, state needs to be an object, that's not the case for useState, when using useState the state can be anything, a string, an object, an array, or a boolean.
import React, { useState } from 'react';function myFunction() {
// this is how we declare a state
const [name, setName] = useState("John")
}
In the example above we declared a state variable, name
, and set that state to “John”. Notice how we used name
and setName
, if compared to a state in a class component, name
is the same as this.state.name
and setName
is the same as this.setState
.
in order to read that state or use it all, we need to do is call name
:
console.log(name)=> John
In a class component it would be something like this:
console.log(this.state.name)=> John
In order to update state we call setState
:
function() {
setName("Karen")
}console.log(name)
=> Karen
When we call setName
is the same as calling this.setState
on a class component.
In a class component the same function will look like this:
function() {
this.setState({
name: "Karen"})
}console.log(name)
=> Karen
useState is a very useful tool since it makes your code look nicer and more organized, it can make it easier to keep track of your states and also to update them as necessary.