The problem is simple: you need to extract some parameters from the browser’s URL. The id of a user, for example.

There are several possible solutions to this problem. The one I’ll show allow you to write:

Below, one of the possible forms the hook useParams can take:

Note the use of the hook useRouter . With it, you can get the properties of the route. The one we need here is location.pathname , the pathname that makes up the URL of the browser.

In lines 8 and 9, we extract the parameters we need, giving to matchPath the pathname and the pattern we want to compare — (.*)?/account/:accountID/user/:userID .

The addition of (.*)? allows you to extract the same parameters from URLs like /any-thing/you-want/here/account/:accountID/user/:userID .

The variable pattern can take any value path-to-regexp@^1.7.0 understands.

If the browser’s URL matches the example’s pattern, we will get an object like {match:{userID: '123456, accountID: 'ABC'}} .

By returning the value of the key match we achieve our goal.

Final Notes

The hook useRouter depends you have installed the version 5.0.0 or newer of react-router or react-router-dom .

Refer to the link to get more details about the installation of those packages.