⚛️ React Q45 / 113

What is useNavigate hook?

AI-Powered Answer ✓ Answered

The `useNavigate` hook is a fundamental feature of React Router v6, designed to allow programmatic navigation within your React applications. It replaces the `useHistory` hook from previous versions and provides a more streamlined and intuitive API for changing routes.

What is `useNavigate`?

useNavigate is a hook provided by React Router DOM that returns a function which you can use to programmatically navigate users to different routes. This is particularly useful for actions like form submissions, clicking buttons that trigger a redirect, or handling authentication flows where navigation isn't directly tied to a <Link> component.

How to Use `useNavigate`

To use useNavigate, you first import it from react-router-dom and then call it within your functional component to get the navigation function. This function can then be called with a path string to navigate.

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

function MyComponent() {
  const navigate = useNavigate();

  const handleClick = () => {
    // Navigate to the /dashboard route
    navigate('/dashboard');
  };

  const handleGoBack = () => {
    // Go back one step in the history stack
    navigate(-1);
  };

  return (
    <div>
      <button onClick={handleClick}>Go to Dashboard</button>
      <button onClick={handleGoBack}>Go Back</button>
    </div>
  );
}

Key Features and Considerations

  • Replacement for useHistory: It's the spiritual successor to useHistory and handles both push and replace functionalities.
  • Returns a Function: Unlike useHistory which returned a history object, useNavigate returns a function directly.
  • Absolute and Relative Paths: You can navigate using absolute paths (e.g., /users/profile) or relative paths (e.g., ../settings).
  • State Passing: You can pass state along with your navigation, which can be accessed on the destination route using the useLocation hook.
  • Directional Navigation: You can navigate forward or backward in the history stack by passing a number to the navigate function (e.g., navigate(-1) to go back, navigate(1) to go forward).
  • Options Object: The navigate function accepts an optional second argument, an options object, to specify replace: true (equivalent to history.replace) or to pass state.

Example with State

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

function SenderComponent() {
  const navigate = useNavigate();

  const sendData = () => {
    navigate('/receiver', { state: { message: 'Hello from sender!' } });
  };

  return (
    <button onClick={sendData}>Send Data to Receiver</button>
  );
}

function ReceiverComponent() {
  const location = useLocation();
  const message = location.state?.message || 'No message received.';

  return (
    <div>
      <h2>Receiver Page</h2>
      <p>Received message: {message}</p>
    </div>
  );
}