Cannot Read Property 'history' Of Undefined (useHistory Hook Of React Router 5)


Answer :

Its because the react-router context isn't set in that component. Since its the <Router> component that sets the context you could use useHistory in a sub-component, but not in that one.


Note to other people that run into this problem and already have wrapped the component with Router component. Make sure that Router and the useHistory hook are imported from the same package. The same error can be thrown when one of them are imported from react-router and the other one from react-router-dom and the package versions of those packages don't match. Don't use both of them, read about the difference here.


useHistory won't work in the component where you have your Routes because the context which is needed for useHistory is not yet set.

useHistory will work on any child component or components which your have declared in your Router but it won't work on Router's parent component or Router component itself.


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?