[Ionic React] Functional component do not get correct location from useLocation hook

Hello there,

I’m facing to an issue which I do not understand.
I created a functional component, and use the hook useLocation from react-router.

If I print the location on a mobile device, I always get the root url /
From computer browser, the location is correct.

Did you already see this problem ?
If I transform my functional component to a class, and use componentDidMount with the withRouter method, it works as expected.
But why there is this problem with FC ?

Thank you in advance for any hint !

Here is my code :

import React, {useEffect} from "react";
import {Network} from "@capacitor/network";
import {useIonAlert} from "@ionic/react";
import {useTranslation} from "react-i18next";
import {useHistory, useLocation} from "react-router";
import {routesUrl} from "../routes/Routes";

const AppNetworkListener: React.FunctionComponent = (props) => {
    const {t} = useTranslation();
    const history = useHistory();
    const location = useLocation();

    const [showNetworkError, hideNetworkError] = useIonAlert();

    // Mimic componentDidMount
    useEffect(() => {
        // Listen for network change
        Network.addListener('networkStatusChange', status => {
            if (status.connected) {
                console.debug(location.pathname, routesUrl.scanner)
            } else {

        // On application load see if the network is available
        Network.getStatus().then(state => {
            if (!state.connected) {
    }, []);

    const showError = (): void => {
            cssClass: 'error-alert',
            backdropDismiss: false,
            header: t('notifications.network_error.header'),
            message: t('notifications.network_error.message')

        // If user is stuck on scanner page redirect it, avoid to continue scanning and getting errors
        // Todo detection of pathname on DEVICE is not correct ! Always return / with functional component, may change this as class and use componentDidMount
        console.debug(location.pathname, routesUrl.scanner)
        if (location.pathname === routesUrl.scanner) {

    return null;

export default AppNetworkListener

I suspect you are seeing the issue because this specific component wasn’t routed to, it’s parent was so the hook doesn’t have the appropriate context. You could just move the routing logic out of this component and pass the appropriate callback function as a property that is called when needed

Thank’s for your reply.
The idea of this component is to have the whole logic of what to do when the application has no network. Then I do not want to move out the routing logic…

I finally transform this functional component in a class component and use componentDidMount, with this approach and by using withRouter decorator I get the correct location state from react-router.

I will definitely don’t understand why in my FC component the context of react-router is not correct :’(