Topic Overview and Actualization

Welcome! Today, we'll journey through the process of programmatic navigation using React Router v6. We'll explore the hooks useNavigate and useLocation, along with a concept known as navigation with state. Let's jump in!

Navigating Programmatically

Typically, a React app that uses Router v6 utilizes Link or NavLink for navigation. However, there are instances when we require more control, such as redirecting after a form submission. That's when we turn to programmatic navigation.

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

function NewPostPage() {
  let navigate = useNavigate();
  
  saveNewPost(newPost).then(() => {
    navigate('/main'); // Navigates the user to the main page after saving a post
  });
}
The Magic of useNavigate

useNavigate hook provides a function enabling navigation in our React router application. In addition to navigating to absolute paths like /login or /home, useNavigate possesses the superpower to navigate relative to the current location. It also introduces a new way to navigate backwards.

For instance, if we wanted to move back one step in our route history, we could call navigate(-1). It's a simple and intuitive feature that can be incredibly handy in certain scenarios.

For example, consider a back button in a multi-step form:

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

const BackButton = () => {
  let navigate = useNavigate();

  let handleClick = () => {
    navigate(-1); // Takes you back one step in your route history.
  };

  return <button onClick={handleClick}>Go Back</button>;
}

Here, when the 'Go Back' button is clicked, the user would be taken back to the previous page in their route history. This beautiful feature brought forth by the useNavigate hook allows us a more human-friendly way of handling navigation in our apps. Continue exploring and you'll find even more friendly features!

Introduction to useLocation

useLocation is another hook offered by React Router. It returns an object representing the current location or URL. This can be useful when you're creating breadcrumbs or displaying the current pathname.

import { useLocation } from 'react-router-dom';

function CurrentPathDisplay() {
  let location = useLocation();
  
  return <div>Your current location: {location.pathname}</div> // Displays the user's current location
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal