DEV Community

quirkybird
quirkybird

Posted on

How do I handle the problem of header not being updated after route conversion in React?

When I was writing a React program, I used the useEffect hook function to update the title after route conversion, and found that when the callback function in Effect was executed, the document.title print value was still the value before the jump, and the useEffect hook function was executed after Dom rendering. But at this time I do not know why the title has not changed, maybe I was wrong at that time, how can it be achieved?

import { useEffect, useRef, useState } from "react";
import { useLocation } from "react-router-dom";

export default function useRouterTracking() {
  const viewNumber = useRef({});
  const location = useLocation();
  const pathname = useRef(null);
  const [title, setTitle] = useState(document.title);

  useEffect(() => {
    console.log(title);
    pathname.current = location.pathname;
    setTitle(document.title); 

    if (title in viewNumber.current) viewNumber.current[title] += 1;
    else viewNumber.current[title] = 1;
  }, [location.pathname, title]);
}
Enter fullscreen mode Exit fullscreen mode

Each time, I print the previous title, which is not what I want, nor is it what a React program should render

Top comments (0)