Structure of useNavigate hook
After importing the useHistory hook, we can call it inside the functional component to get a reference to the history object.
Syntax:
const navigate = useNavigate();
The history
object returned by the useHistory
hook contains some methods that we can use to navigate between routes within the component. Here are some methods:
- navigate(): Navigates to the specified delta in the history stack. The
delta
argument is a number that represents the number of pages to go forward or backward in the history stack. A positivedelta
value will go forward in the history stack, and a negativedelta
value will go backward in the history stack.
Example: Below is the basic implementation of the useNavigation hook.
Javascript
import * as React from 'react' ; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom' ; import Home from './Component/TempConvert' ; import About from './Component/newcom' ; const App = () => ( <Router> <Routes> <Route exact path= "/" element={<Home />} /> <Route path= "/about" element={<About />} /> </Routes> </Router> ); export default App; |
Javascript
import * as React from 'react' ; import { useNavigate } from 'react-router-dom' ; import '../App.css' const Home = () => { const navigate = useNavigate(); const handleClick = () => navigate( '/about' ); return ( <> <h1> Home Page </h1> <button type= "button" onClick={handleClick}> About Page </button> </> ); }; export default Home; |
Javascript
import * as React from 'react' ; import { useNavigate } from 'react-router-dom' ; const About = () => { const navigate = useNavigate(); const handleClick = () => navigate( '/' ); return ( <div> <h1>About Page</h1> <button type= "button" onClick={handleClick}> Home Page </button> </div> ) } export default About; |
Output:
Replacement of useHistory hook in React
In this article, we will learn how to replace the useHistory hook in React. With the introduction of new versions of React Hooks, useNavigate in React replaced the useHistory hook. useNavigate hook is a React hook that allows you to navigate your application imperatively.
Table of Content
- What is useHistory hook?
- What is useNavigate hook?
- Why useHistory hook was deprecated?
- Importing useNavigate hook
- Structure of useNavigate hook
Contact Us