Today's Error Insight : useHistory versus useNavigate in React Router



Today's Error Insight : useHistory versus useNavigate in React Router
Failed to compile ./src/*** Attempted import error: 'useHistory' is not exported from 'react-router-dom'. This error occurred during the build time and cannot be dismissed.
Today, I encountered an error due to the transition from useHistory
to useNavigate
in React Router v6. Often, I find myself reaching for useHistory
out of habit. This time, however, I'm determined to clearly distinguish and understand the usage of both to prevent any confusion.
In React Router, both useHistory
and useNavigate
hooks are used for navigation, but they belong to different versions of the library. Here's a comparison between the two:
useHistory
Hook
- Version: Available in React Router v5.
- Usage: Allows you to access the history instance used by React Router. You can perform navigation, go back, or replace the current state in the navigation stack.
- Example Usage:
import { useHistory } from "react-router-dom";
function MyComponent() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return <button onClick={handleClick}>Go Home</button>;
}
Methods: Offers methods like push()
, replace()
, go()
, goBack()
, and goForward()
for navigating or modifying the navigation history.
useNavigate
Hook
- Version: Introduced in React Router v6, replacing
useHistory
. - Usage: Simplifies the navigation API with a more straightforward approach for programmatic navigation. Instead of getting a history object, you directly get a function to call for navigation purposes.
- Example Usage:
import { useNavigate } from "react-router-dom";
function MyComponent() {
let navigate = useNavigate();
function handleClick() {
navigate("/home");
}
return <button onClick={handleClick}>Go Home</button>;
}
Methods: Primarily provides a single function that can be used for navigation. It can be called with the path to navigate to, and optionally, an options object to replace the current entry in the history stack or to specify how far back or forward to go in the history stack.
Key Differences
- API Simplicity:
useNavigate
offers a simpler and more straightforward API compared touseHistory
. - Version Compatibility:
useHistory
is for React Router v5, whileuseNavigate
is for v6 and above. - Functionality: While both hooks serve the purpose of navigation,
useNavigate
streamlines the process, making it more intuitive to perform common navigation tasks without directly managing the history stack.
In summary, if you are working with React Router v6 or later, you should use useNavigate
for navigation tasks. If you are on React Router v5 or earlier, useHistory
will be your tool for navigation.