The useHistory
hook is part of the react-router-dom
library and is used to manage navigation history in a React application using React Router. It provides access to the history object, which allows you to programmatically navigate to different pages in your application.
Here's a basic example of how to use the useHistory
hook:
react-router-dom
if you haven't already:bashnpm install react-router-dom
jsximport React from 'react';
import { useHistory } from 'react-router-dom';
useHistory
hook in your component:jsxfunction MyComponent() {
const history = useHistory();
const handleButtonClick = () => {
// Use the push method to navigate to a new route
history.push('/new-route');
};
return (
<div>
<h1>My Component</h1>
<button onClick={handleButtonClick}>Go to New Route</button>
</div>
);
}
export default MyComponent;
In this example, when the button is clicked, the handleButtonClick
function is called, which uses the history.push
method to navigate to the '/new-route'. The useHistory
hook gives you access to the history object, which includes methods like push
, replace
, go
, etc.
You can also use the useHistory
hook to go back or forward in the history stack:
jsxconst handleGoBack = () => {
// Go back one step in the history stack
history.goBack();
};
const handleGoForward = () => {
// Go forward one step in the history stack
history.goForward();
};
Remember to wrap your component with a BrowserRouter
or another appropriate router from react-router-dom
in a higher-level component in your application:
jsximport { BrowserRouter as Router } from 'react-router-dom';
function App() {
return (
<Router>
<MyComponent />
{/* Other components and routes go here */}
</Router>
);
}
This ensures that the useHistory
hook has access to the router context.