# React hook - useRef - example timer

## 1. Import các thứ cần thiết
```
import {useState, useEffect, useRef} from 'react'
```

## 2. Tạo ref
```
const interValRef = useRef()
```

## 3. Tạo state timer
```
const [timer, setTimer] = useState(0)
```

## 4. Run timer
```js
useEffect(() => {
  setInterval(() => {
    setTimer(timer => timer + 1)
  }, 1000)
}, [])
```

## 5. Clear interval
```js
useEffect(() => {
  interValRef.current = setInterval(() => {
    setTimer(timer => timer + 1)
  }, 1000)
  return () => {
    clearInterval(interValRef.current)
  }
}, [])

return (
  <button onClick={() => clearInterval(interValRef.current)}>
    Clear Timer
  </button>
)
```

## 6. Demo
<iframe src="https://codesandbox.io/embed/react-hook-useref-example-timer-8inq0?autoresize=1&fontsize=12&hidenavigation=1&theme=dark"
     style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;"
     title="React hook - useRef - Example Timer"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
