History Change shows old page title

Hi,
I have a SPA in React and react-router-dom; I’m trying to track PageViews using Tag Manager.
I have followed these two guides:

So in my custom title is {{PageTitle}} and custom url is {{PageUrl}}.

When the route changes, i update the document title using a useEffect hook

useEffect(() => {
    document.title = title;
  }, [title]);

The page view is being tracked, but the wrong page title is logged: the previous route title (in other words the old title).
The issue is that the HistoryChange is triggered before my hook to update the title.

What can I do? I tried _paq.push(["setDocumentTitle", document.title]); inside the useEffectHook but it’s not seems to work.

For the guys working with React SPAs: what’s the best way to track page views in MTM with the correct title?
The hook is specific for Matomo so I can re-implement the whole update of document title.

Thank you in advance