How to properly use useHistory() from react-router-dom?

React JS Faysal Shuvo

In this article we are answering How to properly use useHistory() from react-router-dom?


React router dom is a npm package. It helps us to use dynamic routing in our web application. It allows us to show pages and users can navigate from one page to another page. React router doms major advantage is when you click a link to go to another page the page does not have to be refreshed. This means the user experience is better and the performance of the app is also better.


useHistory():

In react-router-dom, there is a hook called useHistory(). It helps us access React Router’s history object. Using the history object we can manipulate the state of the browser history. We can redirect users from one page to another. useHistory() is from v5 of react-router-dom. To use useHistory() in your app you have to install v5 using :

npm install react-router-dom@5 

All we need to do is call useHistory() inside a functional component.

import { useHistory } from 'react-router-dom'; 
const App = () => {
          const history = useHistory();
          const redirectHandler = () => {
                 history.push('/home’);
            } return (
                <div>
                     <h1>React-Router</h1>
                     <button onClick={redirectHandler}>Home</button>
                 </div>
    );
};

This is a very simple example of useHistory().

But in version 6 of react-router-dom, they do not use useHistory(). They changed it to useNavigate(). So this is how you do it:

import { useNavigate} from 'react-router-dom'; 
const App = () => {
            const navigate= useNavigate();
            const redirectHandler = () => {
                        navigate('/home’);
            }
            return (
               <div>
                   <h1>React-Router</h1>
                    <button onClick={redirectHandler}>Home</button>
                </div>
    );
};


You can learn more from upgrade from v5 to v6 here and see what more they upgraded. Thanks for reading the article. If you need any more help about useHistory() you can comment below.