Components with internal state
Let's do a little bit more with the button. Let's make it count clicks.
count clicks

Naive implementation

1
const Clicker: React.FC = () => {
2
let clicks = 0;
3
const handleButtonClick = () => {
4
clicks++;
5
}
6
7
return (
8
<button onClick={handleButtonClick}>Clicked { clicks } times</button>
9
)
10
}
Copied!
Boom, done. Except it 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.
1
import React, { useState } from "react"
2
3
const Clicker: React.FC = () => {
4
const [clicks, setClicks] = useState<number>(0)
5
const handleButtonClick = () => {
6
setClicks(clicks + 1)
7
}
8
9
return (
10
<button onClick={handleButtonClick}>Clicked { clicks } times</button>
11
)
12
}
Copied!

Rules of Hooks

There are just two rules you have to remember to use Hooks properly:
  1. 1.
    Only Call Hooks at the Top Level
  2. 2.
    Only Call Hooks from React Functions
Some people say there are just two rules but reality is that they exist to address problems with magic used to implement Hooks.
They make using Hooks harder.

Resources