DEV Community

keeganmcroberts
keeganmcroberts

Posted on

useNavigate Hook in React JS

The useNavigate hook is one of my favorite and easy-to-use hooks while programming with React JS. It offers more functionality of the similar yet antiquated useHistory hook, only with easier compatibility and more features. It presents a very streamlined approach for navigating pages and redirecting to specific URLs of your application.


To Start:

useNavigate requires React Router Dom v6 as it replaced the useHistory hook of older React Router Dom versions. To install this package:

npm install history@5 react-router-dom@6
Enter fullscreen mode Exit fullscreen mode

You will then have to import the hook from React Router into any functional component you wish to implement the hook.

import { useNavigate } from 'react-router';
Enter fullscreen mode Exit fullscreen mode
note: useNavigate can only be used in functional components and cannot be used for class components

Next:

Define a variable equal to the useNavigate hook inside of your functional component. We will call it "navigate" for the purpose of distinctiveness.

let navigate = useNavigate();
Enter fullscreen mode Exit fullscreen mode

Then:

Call the variable anywhere within your component and pass in any route which has been defined in order to redirect to said route. In this instance, we are calling navigate('/shoppingCart') inside of an onClick function in order to re-route to the designated route upon clicking.

function Home() {
  let navigate = useNavigate();
  function redirect() {
    navigate('/shoppingCart')
  }
  return (
    <div>
      <button onClick={redirect}>View Shopping Cart</button>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Additionally:

useNavigate can be passed numerical arguments in order to navigate back to the original page.

function ShoppingCart() {
  let navigate = useNavigate();
  function redirect() {
    navigate(-1)
  }
  return (
    <div>
      <button onClick={redirect}>Back to Home</button>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Here we can see that, instead of a specific route (eg: /home) we pass the numerical argument of -1, which will take us back to the former page.

Similarly, while -1 is passed to useNavigate() in order re-route to the former page, 1 will re-route to the next page held in history.


Thanks for reading and I hope this short tutorial has proven helpful.

Top comments (0)