What is useNavigate hook and how to use it in ReactJS?
The useNavigate hook is a powerful and Intuitive way of navigate between pages in React application. It returns a function that lets us navigate programmatically. It simplifies the process of URL changes.
The navigate function takes to and options as an arguments. The options argument is optional.
Example:
import React from "react";
import {
BrowserRouter as Router,
Routes,
Route,
useNavigate
} from "react-router-dom";
function About( ){
return (
<div>
<h2>About</h2>
</div>
);
}
function Home( ){
const navigate = useNavigate( );
const clickHandler = ( ) => {
navigate( "/about" );
};
return (
<>
<h3>home page </h3>
<button onClick={clickHandler}>Go to About page</button>
</>
);
}
function App( ){
return (
<Router>
<Routes>
<Route path="/about" element={<About/>}/>
<Route path="/" element={<Home />}/>
</Routes>
</Router>
);
}
export default App;