RouteComponentProps vs useHistory

Viewed 847

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 = ({
    text
  }: PropsType) => {
    const history = useHistory();
};
1 Answers

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.

Related