useNavigate tutorial React JS

Saleh Mubashar - Oct 28 '21 - - Dev Community

Hi guys !.

In this post we will learn how to use the useNavigate hook in React JS. useNavigate is part of React Router and has replaced useHistory, although it is similar to useHistory, but with more useful features.

useNavigate is a new hook introduced in React Router v6 and it is extremely useful and easy to use.

Uses:

  1. Go to the previous or next pages
  2. Redirect user to a specific Url

Check out my blog.


Step 1:

Install React Router as useNavigate is part of the react router dom package. Install using the following 2 commands:

Note : useNavigate is only available in React Router Dom v6

npm install history@5 react-router-dom@6

Step 2:

Import useNavigate from React Router using the following code. This line of code can be added in any react class or function (however we are using a functional component in this example).



import { useNavigate } from 'react-router';


Enter fullscreen mode Exit fullscreen mode

Step 3:

Now we will assign the useNavigate() function to a variable for ease of use. Add the following code:



let navigate = useNavigate();


Enter fullscreen mode Exit fullscreen mode

Step 4:

Now you can use the variable name anywhere to navigate to a page, previous page or next page.

Example 1:

Redirect user to another page:



function Redirect() {
  let navigate = useNavigate();
  function handleClick() {
    navigate('/home')
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

In the above code, the navigate('/home') is used to redirect the user on button click.

Example 2:

In this example, we will see how to redirect to previous page:



function Redirect() {
  let navigate = useNavigate();
  function handleClick() {
    navigate(-1)
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

Example 3:

In this example, we will see how to redirect user to the next page (in history)



function Redirect() {
  let navigate = useNavigate();
  function handleClick() {
    navigate(1)
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );


Enter fullscreen mode Exit fullscreen mode

As you can see in the above two examples, -1 is used to go to the previous page while 1 is used to go to the next page.


Check Out my latest tutorial on Hubapages

Thank you all for reading this post!
If you learnt something new, you can buy me a coffee to support my work!
Cheers! 🎉

Buy Me A Coffee

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player