Skip to main content

Command Palette

Search for a command to run...

React hook - useRef - example timer

Updated
•1 min read•View as Markdown
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

useEffect(() => {
  setInterval(() => {
    setTimer(timer => timer + 1)
  }, 1000)
}, [])

5. Clear interval

useEffect(() => {
  interValRef.current = setInterval(() => {
    setTimer(timer => timer + 1)
  }, 1000)
  return () => {
    clearInterval(interValRef.current)
  }
}, [])

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

6. Demo

ReactJS

Part 2 of 19

ReactJS là một thư viện JavaScript mã nguồn mở được thiết kế bởi Facebook để tạo ra những ứng dụng web hấp dẫn, nhanh và hiệu quả với mã hóa tối thiểu. Series hướng dẫn học ReactJS cơ bản.

Up next

React hook - useRef - auto focus input

useRef giúp chúng ta thao tác và xử lý DOM 1. Import các thứ cần thiết import { useEffect, useRef } from 'react' 2. Tạo ref const inputRef = useRef() 3. Gắn ref vào input <input type="text" ref={inputRef} /> 4. Tự động focus khi page loaded useEffect...

More from this blog

KenTrung VN

23 posts

Mình mới ba mấy tuổi thôi mà đứng dậy nhanh quá đã hơi chóng mặt 🤪🤪🤪