DEV Community

Cover image for React Router Hooks Guide
Sackett Keesen
Sackett Keesen

Posted on

React Router Hooks Guide

React Router is a library that was created to help create navigation links in a website. Similar to how the react library gives us hooks to more easily create the user interface of a web application the React Router library gives use hooks and tools to add navigations routes in a simpler fashion to our applications' going to cover some of the commonly used hooks in React Router and explain what they are used for.

useNavigate()

One of the most useful hooks included in the react router library is the useNavigate() hook. The useNavigate() hook does what the name implies and allows you to add a navigation route to a component within your application. For example if you had a webpage that showed a list of properties and once a property was clicked it would navigate the user to a new page that only showed that properties details you could use the useNavigate() hook to tell your website where to take the user once they click on the property. This is also an extremely useful tool when creating a navbar. You can create a route for each link in the navbar to bring the user to your desired route.

useParams()

Another very useful hook in the library is useParams(). This tool is used to use dynamic information from the URL of the route. This is a great tool when you are trying to get create a route that is directed towards a specific user ID. You will need the dynamic ability of useParams() to take the user ID out of the URL route and then you can use it in your code via useParams() to fetch and generate specific details based on the object ID. A good example of this is if you were creating a website that sold different products. When the user clicks on a product you want them to be directed to a page that gives additional details on that product including price, weight, shipping etc... those details are custom to each product being sold so you need the unique identifier(ID) from the URL Route to run through your fetch and to populate the new page the user is on.

useLocation()

useLocation() is a tool that gives us back an object of the information within the URL. This is similar to useParams() but gives us additional information. This tool can be useful for tracking views of a specific URL. Say you want to know how many views each product on your website is getting. Well based off of the unique link for each product and the useLocation() hook you can track the amount of views through creating a function that adds a counter every time the specific location is visited.

There are many more useful react router hooks that can be used but the key is practice. Make sure you stay refreshed on the official react router documentation linked here https://reactrouter.com/en/main.

Top comments (0)