Published: October 07 2021

React - history listen and unlisten with React Router v5

This is a quick example of how to register and unregister a location change listener in a React component with React Router v5. Location change listeners allow a component to listen to route changes in a React app and execute a function when they happen, it's important to unregister location change listeners (unlisten) when a React component unmounts to prevent memory leaks in an app.

The below code snippet is from a React + Recoil Login tutorial I posted recently, to see the code running in a live demo app check out React + Recoil - User Registration and Login Example & Tutorial.

 

React Alert Component with history.listen & unlisten

Path: /src/_components/Alert.jsx

The alert component renders the alert from recoil state with bootstrap CSS classes, if the Recoil alert atom contains a null value nothing is rendered for the component.

The component registers a route change listener on mount in the useEffect() hook by calling the history.listen() function with the callback alertActions.clear which clears alert notifications on route change. The history.listen() function returns another function to unregister the listener when it is no longer needed, this is assigned to the unlisten variable and returned by the useEffect() hook so it will be called on component unmount.

import { useEffect } from 'react';
import { useRecoilValue } from 'recoil';

import { alertAtom } from '_state';
import { useAlertActions } from '_actions';
import { history } from '_helpers';

export { Alert };

function Alert() {
    const alert = useRecoilValue(alertAtom);
    const alertActions = useAlertActions();

    useEffect(() => {
        // clear alert on location change
        const unlisten = history.listen(alertActions.clear);

        // stop the listener when component unmounts
        return unlisten;

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    if (!alert) return null;

    return (
        <div className="container">
            <div className="m-3">
                <div className={`alert alert-dismissable ${alert.type}`}>
                    <a className="close" onClick={alertActions.clear}>&times;</a>
                    {alert.message}
                </div>
            </div>
        </div>
    );
}

 


Need Some React Help?

Search fiverr for freelance React developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by