useNavigate() hook in React

useNavigate() hook in React

Introduction:

React is one of the most widely used front-end frameworks for building modern web applications. As developers, we often need to handle the routing and navigation of our applications. React Router is a popular library that provides a declarative way to handle routing in React applications. In this article, we will discuss the useNavigate() hook provided by React Router v6.

What is useNavigate() hook?

The useNavigate() hook is a new addition to React Router v6. It provides a simple and efficient way to navigate to a different route in your React application. You can think of it as a replacement for the useHistory() hook provided by React Router v5.

The useNavigate() hook returns a navigate() function, which can be used to navigate to a different route. The navigate() function takes a single argument, which is the path you want to navigate to. You can also pass an optional second argument, which is an object containing state that you want to pass along with the navigation.

Syntax:

scssCopy codeconst navigate = useNavigate();
navigate('/dashboard');

Example:

Let's consider an example where we have a simple React component that renders a button. On clicking the button, we want to navigate to a different route.

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

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

  function handleClick() {
    navigate('/dashboard');
  }

  return (
    <div>
      <h1>Home Page</h1>
      <button onClick={handleClick}>Go to Dashboard</button>
    </div>
  );
}

export default Home;

In the above example, we are importing the useNavigate() hook from the 'react-router-dom' package. We are then initializing a navigate variable using the useNavigate() hook. Inside the handleClick() function, we are using the navigate() function to navigate to the '/dashboard' route.

Conclusion:

In this article, we discussed the useNavigate() hook provided by React Router v6. We learned how to use the useNavigate() hook to navigate to a different route in our React application. The useNavigate() hook provides a simple and efficient way to handle navigation in React applications. I hope this article helped you understand the useNavigate() hook and how to use it in your React projects.