React Hooks: useState
From React there is a new way of managing state in functional components, using hooks. One of it is useState
where we can get and set state values in functional components.
To utilize useState
in our functional components we need to understand its parts. There are two important parts, the variable from useState
and function which set the said variable. These two parts are destructured array values from useState
const [theVariable, setTheVariable] = React.useState("initial value")
The useState
accept initial value which we can define. theVariable
will contain the state in the useState
then the setTheVariable
is a function which accept value that set theVariable
A more complete functional component example utilizing useState
as follows:
import React from "react"
export default function App() {
const [buttonToggle, setButtonToggle] = React.useState(false)
return (
<div className="App">
<button
style={{ backgroundColor: buttonToggle ? "transparent" : "yellow" }}
onClick={() => {
setButtonToggle(!buttonToggle)
}}
>
Toggle
</button>
</div>
)
}
Here the useState
contains the boolean value which is used as the toggle indicator for the button Toggle
.
Reference: