What is the difference between useHistory() and props.history in React Route
Asked Answered
S

1

9

In my react function, I could write:

const history = props.history; or const history = useHistory();

Then I can use history.push() or history.goBack() in the same way.

So I wonder if they are different or not?

Sherrie answered 18/12, 2019 at 15:47 Comment(6)
You can use useHistory() in any component, but props.history only in components where the history is available in props.Quesnay
When I use Router, it seems the history prop was available for each route component without adding any extra code.Sherrie
But does it get passed to the nested/children components?Quesnay
I see, thank you. So they are the same but for different scenario.Sherrie
@JTang, im using connected-react-router, will i get props.history for all the components?Mathes
Does this answer your question? RouteComponentProps vs useHistoryPu
K
1

Few Differences in this two

  1. useHistory() is react hook and props.history is properties of props
  2. we cannot use useHistory() in class component.
  3. we cannot use props.history in functional component directly, for that we have to wrap the component with withRouter. please follow this link click here

conclusion : if you are using class component then use props.history and if you are using functional component then use useHistory() hook

Keeter answered 30/5, 2022 at 6:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.