The useNavigate() hook is introduced in the React Router v6 to replace the useHistory() hook. In the earlier version, the useHistory() hook accesses the React Router history object and navigates to the other routers using the push or replace methods. It helps to go to the specific URL, forward or backward pages. In the updated version, the React Router’s new navigation API provides a useNavigate() hook which is an imperative version to perform the navigation actions with better compatibility.
Now let’s understand the working of useNavigate() hook using examples.
Creating React application and installing module:
Step 1: To start with, create a React application using the following command:
npx create-react-app <project_name>;
Step 2: Install the latest version of react-router-dom in the React application by the following.
npm install react-router-dom
Project Structure: Create a folder named components in the src folder and add files Home.js and About.js to it. The folder structure will look like the following:
Example: In this example, we will use useNavigate() hook to navigate to the about page and to go back to the home page. From the following code, the user can go back to the Home page from the About page on the button click.
Home.js
import React from 'react' ; import {useNavigate} from "react-router-dom" const Home = () => { const navigate = useNavigate(); return ( <> <h1 style={{color: "green" }}>GeeksForGeeks</h1> <button onClick={()=>navigate( "/about" )}>About</button> </> ) }; export default Home; |
About.js
import React from 'react' ; import {useNavigate} from "react-router-dom" const About = () => { const navigate = useNavigate(); return ( <> <h1 style={{color: "green" }}>A Computer Science portal for neveropen.</h1> <button onClick={()=>navigate(-1)}>Go Back Home</button> </> ) }; export default About; |
Note: Here, the numerical argument has passed to move the history stack pointer.
App.js
import React from "react" ; import {BrowserRouter,Routes,Route} from "react-router-dom" ; import Home from "./components/Home" ; import About from "./components/About" ; function App() { return ( <> <BrowserRouter> <Routes> <Route exact path= "/" element={<Home/>}/> <Route exact path= "/about" element={<About/>}/> </Routes> </BrowserRouter> </> ); } export default App; |
Step to run the application: Open the terminal and type the following command.
npm start
Output: Similarly, we can pass the numerical arguments to go forward.