Using React Router Part-2

React Router Hooks

Now that you understand why Hooks are added for routing, let’s see the Hooks in action.

useParams

The useParams Hook returns an object containing key-value pairs of the passed parameters in a dynamic URL.

For example, let’s say you have a User page component that accepts an id as a param in the URL.

Import the useParam Hook from react-router-dom package.

Now you can use the Hook, as shown below.

  console.log(params);  return (
// ...
)
}

So if you were to pass 3 as ID in the user URL (/user/3), the useParam() would return an object as follows:

You can use this id param to display on the page or fetch the user information from the server.

// /user/:id
const User = () => {
const params = useParams();
return (
<div>
<div>This is the user page</div>
<div>current user Id - {params.id}</div>
</div>
);
};

useHistory

The useHistory Hooks return the history object, which the router uses internally to handle the route changes. The history object is used for managing session history.

For example, you can use the history.push() method to add a new entry to the history stack and navigate the user from the current route:

const User = () => {
const history = useHistory();
const params = useParams();
const handleBack = () => {
history.goBack();
};
const handleNavigation = () => {
history.push("/user/5");
};
return (
<div>
<div>This is the user page</div>
<div>current user Id - {params.id}</div>
<div>
<button onClick={handleBack}>Go Back</button>
</div>
<div>
<button onClick={handleNavigation}>Go To Different User</button>
</div>
</div>
);
};

In the code block above, two buttons are added to the User page component: one button to take the user to the previous page and another to navigate the user to a different page. The history.goBack() method navigates the user to the previous page and goes back one entry in the history stack.

useLocation

The useLocation Hook allows you to access the location object that represents the active URL. The value of the location object changes whenever the user navigates to a new URL.
The useLocation Hook can be convenient when you have to trigger any event whenever the URL changes.

Consider that you have to keep track of views on users’ profile pages. You can detect changes in the location object using the useEffect Hook, which comes with React.

const User = () => {
const history = useHistory();
const params = useParams();
const location = useLocation();
useEffect(() => {
console.log(location.pathname);
// Send request to your server to increment page view count
}, [location]);
const handleBack = () => {
history.goBack();
};
const handleNavigation = () => {
history.push("/user/5");
};
return (
<div>
<div>This is the user page</div>
<div>current user Id - {params.id}</div>
<div>
<button onClick={handleBack}>Go Back</button>
</div>
<div>
<button onClick={handleNavigation}>Go To Different User</button>
</div>
</div>
);
};

useRouteMatch

The useRouteMatch Hook matches the active URL with a given path, similarly to how the Route component works. It’s a very interesting Hook; you can get rid of the unnecessary Route component and access the match object.

You can now change the path in the user page’s route component to simply /user:

Then, use the routeMatch Hook, as shown below:

const User = () => {
const history = useHistory();
const routeMatch = useRouteMatch("/user/:id");
const location = useLocation();
useEffect(() => {
console.log(location);
}, [location]);
const handleBack = () => {
history.goBack();
};
const handleNavigation = () => {
history.push("/user/5");
};
return (
<div>
<div>This is the user page</div>
{routeMatch ? (
<div>user Id - {routeMatch.params.id}</div>
) : (
<div>You are viewing your profile</div>
)}
<div>
<button onClick={handleBack}>Go Back</button>
</div>
<div>
<button onClick={handleNavigation}>Go To Different User</button>
</div>
</div>
);
};

The useParams hook will not return an empty object since the Route component did not have any route params specified. Instead, you now have access to params in the routeMatch object.

Conclusion

Hooks are a great addition to the React ecosystem. Now that you’ve seen some code on handling routing with Hooks, you’re ready to take full advantage of what they have to offer.

Until next time, stay safe and keep coding with React Hooks!

A tech enthusiast and a die hard lover of JavaScript.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store