Navigating React.js with useNavigate

ericamayes

Erica Mayes

Posted on October 11, 2022

Navigating React.js with useNavigate

In the process of building my first two end-of-phase projects at Flatiron, I happened upon a handful of terms and concepts outside of my curriculum that proved quite useful.

This was no different in Phase 3, and my project partners and I soon stumbled across a very helpful little React hook called useNavigate. Below I've included a brief overview and a specific use case for the useNavigate hook.

Under the Hood

At first glance, useNavigate functions very similarly to its predecessor - useHistory - in that it gives you the ability to navigate programmatically. Prior to React v6, useHistory would hook into React Router's history object and utilize push and replace methods to maneuver to other routers. useNavigate performs similar functionality, but with better compatibility and built-in convenience functions.

Specifically, useNavigate is a hook that affords access to the navigation object. While every screen component in an application is provided with the navigation prop by default, it is often inconvenient or not functional to pass the navigation prop to a child component directly - enter useNavigate!

useNavigate in Action

Let's take a look at a specific use case scenario.

To start, we'll set up a React app with the latest version of the react-router-dom installed by running these two terminal commands (if using npm):

npx create-react-app <project_name>
npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

To demo the capabilities of useNavigate, we'll set up a basic App with two components as children of App.js - About & Contact.

Next, we have to import React and useNavigate to every file we plan to use them - in our case, both About.js and Contact.js.

import React from 'react';
import { useNavigate } from "react-router-dom";
Enter fullscreen mode Exit fullscreen mode

Let's create some boiler-plate code:

import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from "./components/Home";
import Contact from "./components/Contact";

function App() {

  return (
      <div>
        <Router>
          <Routes>
            <Route exact path="/" element={
              <Home/>
            }/>
            <Route exact path="/about" element={
              <Contact/>
            }/>
          </Routes>
        </Router>
      </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

At the top level, we've imported React Router and set up our various routes.

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

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

    return (
        <div>
            <h1 style="text-align:center; color:green">The Fellowship of the Ring</h1>
                <ul>
                    <li>Frodo</li>
                    <li>Sam</li>
                    <li>Merry</li>
                    <li>Pippin</li>
                    <li>Aragorn</li>
                    <li>Boromir</li>
                    <li>Legolas</li>
                    <li>Gimli</li>
                    <li>Gandalf</li>
                </ul>
            <button onClick={ () => navigate("/contact")}>Contact</button>
        </div>
    )
};

export default Home;
Enter fullscreen mode Exit fullscreen mode

In the Home component, we passed useNavigate a specified route ("/contact"), and then called it inside a click event.

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

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

  return (
  <div>
     <h1 style="text-align:center; color:red">To contact:</h1>
        <p>The Council of Elrond</p>
        <p>Rivendell</p>
     <button onClick={()=>navigate("/home")}>Home</button>
  </div>
  )
};

export default Contact;
Enter fullscreen mode Exit fullscreen mode

In this demo, the useNavigate hook is being used to toggle between a "Home" and "About" page via a button click.

Further Color

A few notes about the above code:

The navigate function can be passed two types arguments: 

  • A 'to' value (in the same style as the '' tag
  • A delta to point to a location in the history stack

For example: navigate(-1) is used to redirect the user to the previous page in history, while navigate(1) points them to the next page.

Additionally, the navigate prop has a number of convenient built-in functions. To outline a few:

  • reset - replaces the current state with a new route

  • goBack - moves back in the stack in history

  • setParams - alters the route's params

  • setOptions - edits the screen's options

  • isFocused - confirms the screen is focused

Overall, a very useful hook with lots of built-in functionality! Happy coding!

💖 💪 🙅 🚩
ericamayes
Erica Mayes

Posted on October 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related