React-Router useHistory Hook with TypeScript: A 2026 Guide
Explore how to use the React-Router useHistory hook with TypeScript for type-safe, programmatic navigation in React applications.
React-Router useHistory Hook with TypeScript: A 2026 Guide
React Router is a fundamental library for React applications, enabling powerful client-side routing. As applications grow, leveraging TypeScript with React Router can enhance type safety and code readability. This guide focuses on using the useHistory hook in a TypeScript environment, a common necessity when navigating between pages programmatically.
Key Takeaways
- Understand how to integrate
useHistorywith TypeScript in React applications. - Learn to navigate programmatically using
history.push. - Implement state management within history for cleaner code transitions.
- Discover common pitfalls and troubleshooting techniques.
In this tutorial, we'll explore how to use the useHistory hook within a functional component using TypeScript. We will cover setting up a simple React application, integrating React Router, and implementing navigation logic with type safety. Understanding this will improve your ability to manage app navigation effectively, enhancing the user experience.
Prerequisites
- Basic understanding of React and JavaScript.
- Familiarity with TypeScript basics.
- Node.js (v16.0.0 or later) and npm installed on your system.
- React Router v6.0.0 or later installed.
Step 1: Set Up Your React Project
First, create a new React project using create-react-app with TypeScript.
npx create-react-app my-router-app --template typescriptNavigate into the project directory:
cd my-router-appEnsure React Router is installed:
npm install react-router-domStep 2: Configure React Router
Inside your src folder, create a Routes.tsx file to define your application routes. This file will serve as the central hub for your routing logic.
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import LastScreen from './components/LastScreen';
const Routes: React.FC = () => {
return (
);
};
export default Routes;Step 3: Implement useHistory in a Component
Now, let's use the useHistory hook in a functional component. This example will illustrate navigating to a different route based on a condition.
import React, { useEffect } from 'react';
import { useHistory } from 'react-router-dom';
interface Props {
question: string;
selectedAnswer: string | undefined;
}
const LastScreen: React.FC = ({ question, selectedAnswer }) => {
const history = useHistory();
useEffect(() => {
if (selectedAnswer) {
const id = 'unique-id'; // replace with logic to generate a unique ID
history.push({
pathname: `/p/${id}`,
state: { question, selectedAnswer },
});
}
}, [selectedAnswer, history, question]);
return (
Last Screen
Question: {question}
Selected Answer: {selectedAnswer}
);
};
export default LastScreen;This component uses the useHistory hook to navigate to a new path with a dynamically generated ID when a selected answer exists.
Step 4: Handle State with History
Passing state with history.push is a powerful feature that allows you to carry data across routes without global state management.
history.push({
pathname: '/new-route',
state: { key: 'value' }
});Access this state in the target component:
const location = useLocation<{ key: string }>();
console.log(location.state.key);Common Errors/Troubleshooting
- Error: Cannot read property 'push' of undefined
Solution: EnsureuseHistoryis used within aRoutercontext. - Error: Argument of type 'string' is not assignable to parameter of type 'never'
Solution: TypeScript type inference may require explicit type annotations.
Frequently Asked Questions
What is the useHistory hook?
The useHistory hook is a React Router hook that allows you to programmatically navigate through the history stack.
Why use TypeScript with React Router?
TypeScript provides compile-time type checking which helps catch errors early and improves code quality and maintainability.
How do I pass data between routes?
Data can be passed using the state property of history.push and accessed in the destination component.
Frequently Asked Questions
What is the useHistory hook?
The useHistory hook is a React Router hook that allows you to programmatically navigate through the history stack.
Why use TypeScript with React Router?
TypeScript provides compile-time type checking which helps catch errors early and improves code quality and maintainability.
How do I pass data between routes?
Data can be passed using the state property of history.push and accessed in the destination component.