DEV Community

Cover image for useNavigate,Navigate and useLocation in React Router v6
Shahid Alam
Shahid Alam

Posted on

13 1

useNavigate,Navigate and useLocation in React Router v6

What is useLocation?

useLocation is hook that allows us to get the current location(or URL) of the web app.



const currentLocation = useLocation()
console.log(currentLocation)


Enter fullscreen mode Exit fullscreen mode

What is useNavigate?

useNavigate is a hook that allows to create a function that'll help a user navigate to a particular page (based on an action). You can customize it to redirect the user to the login page or user Dashboard.



import React from "react";
import { useNavigate } from "react-router-dom";

const Home = () => {
  const navigate = useNavigate();

  return (
    <div>
      <h2>Visit my profile</h2>
      <button
        onClick={() => {
          console.log("redirecting.....");
          navigate("/profile");
        }}
      >
        My Profile
      </button>
    </div>
  );
};

export default Home;



Enter fullscreen mode Exit fullscreen mode

Now what if you want to go back to the Home page without clicking the browser "Back" button? We provide a button.



import React from "react";
import { useNavigate } from "react-router-dom";

const Profile = () => {
  const navigate = useNavigate();

  return (
    <div>
      <h2>You are awesome!</h2>
      <button
        onClick={() => {
          console.log("redirecting.....");
          navigate(-1);
        }}
      >
        Home
      </button>
    </div>
  );
};

export default Home;



Enter fullscreen mode Exit fullscreen mode

What is Navigate?

Navigate is basically useNavigate() converted into a React component. This makes it easy to implement in our React apps.

props it takes -

  • state - optional -> stores state and can be used to store the location of the current or previous page
  • replace - optional -> helps in redirecting to the location specified in the state.


 return (
    <BrowserRouter>
      <Container maxWidth="lg">
        <Navbar />
        <Routes>
          <Route exact path="/"  element ={<Home/>} />
          <Route path="/auth"  element={<Auth/>} />
          <Route path="/posts" exact element={<Home/>} />
{/*
the Navigate component redirects the user to posts section on getting rendered.
This happend IF the user is logged in(user object is present).
*/}
          <Route path="/auth" exact element={() => (!user ? <Auth /> : <Navigate to="/posts" />)} />
        </Routes>
      </Container>
    </BrowserRouter>
  )
};


Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
arjinalbay profile image
Arjin

thanks :)

Collapse
 
abhijivani3001 profile image
Abhi Jivani

what if i want to restrict user to not go to the previous route. or want to remove previous visited pages.?

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay