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.


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.



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.

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