Routing middleware

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

import {useNavigationComplete, useNavigationStart} from 'routescape';

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

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

    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 useNavigationComplete() callback is first called when the component gets mounted if the route is already in the navigation-complete state.