Navigation in React.js, or useParams, useHistory, useLocation hooks — part 2

Photo by Ferenc Almasi on Unsplash

In the first part, we have seen how to set up our client-side routing using react-router-dom. In this part, we are going to explore some of the very useful hooks from react-router-dom.

Have you ever noticed that most websites use dynamic routes, for example, if you visit an article on a blogging website its URL should probably be like exampleblog.com/post/how-to-write-blog matching its title. Probably they don’t create every new route for their article manually. What they use is dynamic routing, the title here /how-to-write-blog is URL parameter, and depending on this our page would retrieve data needed for this title. Let’s try to mimic this behavior on react. First, we should declare which route is going to be a dynamic route, we do that using a semicolon and giving a name to our parameter, like this /post/:postId and specify a single component which gets rendered for every route starting with /path/ .

Now to get the value of our :postIdparameter we should use useParams hook which comes from react-router-dom. This hook returns us an object containing all parameters and values present in our route.

Now, let’s say we go to /post/some-title route. We see in console this: {postId: "some-title"} using this information we can query some data from our backend or display it on screen, whatever you want to do. The number of params are not limited, you set-up as many route params as you want, like this: /post/:title/:postId/:publisherId all params would be returned in useParams() hook.

useLocation() hook is used to get information about the current route. It returns an object containing current pathname, route queries, and hash. For example, if we go to /post/hello-world?mode=dark&src=main#start useLocation returns

Unlike previous hooks which gave information about the route’s state, this one helps us to manipulate it. It has a lot of methods which we can use in different purposes.

Assume that we instantiated like this: const history = useHistory();

history.push(str) — this method is very useful when you want to navigate to other routes without using Link component when some kind of action happens like a button click, it takes one string argument which is the new route you want to go.

history.goBack(), history.goForward() — as you can tell by their name, these methods help to simulate the browser’s back and forward button behaviors.

And there are some more methods which I am not going to explain, as I have little or no experience using them but feel free to experiment and explore these methods: createHref(), replace(), go(), block(), listen().

Note that all of these hooks are not available outside, BrowserRouter or Router components.

I hope this article helps you. I would be happy to hear from you about quality of this article and look forward to any suggestions about improving my writing and teaching skills.

React dev.