[React] CustomHook 👉 useTitle

4719 ワード

https://nomadcoders.co受講後にまとめられた内容です.

1.UseTitleとは?


これを変えろ!

2.ユーザー見出しの作成

import React, { useEffect, useState } from "react";

const useTitle = (initialTitle) => {
  const [title, setTitle] = useState(initialTitle);
  const updateTitle = () => {
    // index.html에 있는 title 태그
    const htmlTitle = document.querySelector("title");
    htmlTitle.innerText = title;
  }
  // 타이틀이 변경될 때 updateTitle
  useEffect(updateTitle, [title]);
  return setTitle;
}

export default useTitle;

3.UserTitleの使用

  • settimeoutも簡単に使えます.
  • const App = () => {
      const titleUpdater = useTitle("Loading...");
      setTimeout(() => titleUpdater("Home"), 5000);
    
      return (
        <div className="app">
        	hellow
        </div>
      ) 
    }