T8 React Router

Middleware

The useNavigationStart() and useNavigationComplete() hooks define routing middleware, that is intermediate actions to be done before and after the route navigation occurs:

import { useNavigationComplete, useNavigationStart } from "@t8/react-router";

function setTitle(href) {
  if (href === "/intro")
    document.title = "Intro";
}

let App = () => {
  let { route } = useRoute();
  let [hasUnsavedChanges, setUnsavedChanges] = useState(false);

  let handleNavigationStart = useCallback(nextHref => {
    if (hasUnsavedChanges)
      return false; // prevents navigation

    if (nextHref === "/intro") {
      route.assign("/"); // redirection
      return false;
    }
  }, [hasUnsavedChanges, route]);

  useNavigationStart(handleNavigationStart);
  useNavigationComplete(setTitle);

  return (
    // app content
  );
};

This example shows some common examples of what can be handled with routing middleware: preventing navigation with unsaved user input, redirecting to another location, setting the page title based on the current location.

🔹 The callback of both hooks is first called when the component gets mounted if the route is already in the navigation-complete state.