useLocation VS useRouteMatch

useLocation VS useRouteMatch

what is different between useLocation and useRouteMatch as they are both used to access current Path and URL?

useLocation

Provides access to the location prop in React Router

const location = useLocation();

It is similar to window.location in the browser itself, but this is accessible everywhere as it represents the Router state and location.

A primary use case for this would be to access the query params or the complete route string.

const queryParams = new URLSearchParams(location.search);

or

history.push(`${location.pathname}?sort=${(isSortingAscending ? 'desc' : 'asc')}`);

useRouteMatch

Provides access to the match object

If it is provided with no arguments, it returns the closest match in the component or its parents.

const match = useRouteMatch();

A primary use case would be to construct nested paths.

For Links:

<Link to={`${match.url}/comments`} className='btn--flat'>

For Routes :

<Route path={`${match.path}/comments`}>
                <Comments />
            </Route>

instead of :

<Route path={`/quotes/${params.quoteId}/comments`}>