State
Let's do a little bit more with the button. Let's make it count clicks.
Naive implementation
const Clicker: React.FC = () => {
let clicks = 0;
const handleButtonClick = () => {
clicks++;
}
return (
<button onClick={handleButtonClick}>Clicked { clicks } times</button>
)
}
Boom, done. Except is doesn't work, because React has no idea that it should rerender the Clicker
component or keep track of the clicks
variable.
Using the useState
hook
Current Industry Best Practice ™ for keeping track of the state. Previously, we would use class components, but hooks have some advantages over them.
import React, { useState } from "react"
const Clicker: React.FC = () => {
const [clicks, setClicks] = useState<number>(0)
const handleButtonClick = () => {
setClicks(clicks + 1)
}
return (
<button onClick={handleButtonClick}>Clicked { clicks } times</button>
)
}