DEV Community 👩‍💻👨‍💻

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

Posted on

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

"console-results"

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

Oldest comments (0)

Classic DEV Post from 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!