React hook - customHook - useDocumentTitle

React hook - customHook - useDocumentTitle

·

1 min read

1. Chưa sử dụng customHook

import {useState, useEffect} from 'react'

export default function DocumentTitle() {
  const [count, setCount] = useState(0)

  useEffect(() => {
    document.title = `Count ${count}`
  }, [count])

  return (
    <button
      className="btn btn-outline-primary"
      onClick={() => setCount(count + 1)}
    >
      Count - {count}
    </button>
  )
}

2. Sử dụng customHook

import {useEffect} from 'react'

export default function useDocumentTitle(count) {
  useEffect(() => {
    document.title = `Count ${count}`
  }, [count])
}
import {useState} from 'react'
import useDocumentTitle from '../hooks/useDocumentTitle'

export default function DocumentTitle() {
  const [count, setCount] = useState(0)
  useDocumentTitle(count)

  return (
    <button
      className="btn btn-outline-primary"
      onClick={() => setCount(count + 1)}
    >
      Count - {count}
    </button>
  )
}

3. Demo