Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Using React functional components and Typescript, would there be any difference between using the useHistory hook vs RouteComponentProps (react router v5.1)?
Example using RouteComponentProps :
import { RouteComponentProps } from 'react-router-dom';
interface PropsType extends RouteComponentProps {
text: string;
const MyFunctionalComponent = ({
text,
history
}: PropsType) => {
Example using useHistory:
import { useHistory } from 'react-router-dom';
interface PropsType {
text: string;
const MyFunctionalComponent = ({
}: PropsType) => {
const history = useHistory();
I am exactly in the same situation, and I want to share my conclusions with you.
First of all, the behavior of the programatic navigation with both approaches is the same, as they both use the same history
instance, but there are some differences in the way of using them:
Using the member history
of RouteComponentProps
forces you to drill it all the way down your component tree using props. There is nothing wrong with this approach, but if your component tree grows you may find yourself drilling through many layers of components.
Using useHistory
hook you can avoid the previous prop drilling and just allow you to use the history
instance in any functional component. Note that this hook is a quick stopgap for a future hook and will be replaced eventually by a useNavigate
hook.
Personally, I find the useHistory
hook a cleaner and more readable solution for long component trees, but I keep using the history
instance of RouteComponentProps
if the component is close or a direct child of a Route
component.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.