How to convert withRouter to a React hook

The User Experience 🙃

I start every project by asking the question, “What do I want to do?” This does not mean, “How do I want to implement this feature?” It means, as a developer, how do I wish this feature was already implemented. What do I want to have to do to use this feature in the future? How do I make it intuitive and easy to use?

The Implementation

The Dependencies 👶

First, our dependencies.

The Hook 🎣

With our dependencies imported, we can begin writing the hook

The Pub-Sub 📰

To implement pub-sub behavior, we will want to useEffect. This will allow us to subscribe on component mount and unsubscribe on component unmount. Theoretically, it will unsubscribe from an old context and re-subscribe to a new one if the router context were to change (a desirable behavior if that were to happen), but there’s no reason to assume that will ever happen.

Subscribe and unsubscribe during the component lifecycle.
mount > effect1 ... effect2 > update > effect1 ... effect2 > unmount
If the router context has not changed, don’t subscribe or unsubscribe during updates.
When the router history changes, update this component.
On unmount, call the function returned by listen.
The effect is to subscribe and return the unsubscribe function.

Where to Go From Here? 🔮

The HOC implementation of withRouter provided by the react-router package pulls history, location, and match from component props and gives them higher priority than the context API’s values. This is likely due to the <Route> component providing these as props, and match’s value needing to come from Route's path interpretation.

Conclusion 🔚

If you want to contribute to this open-source package or see it in TypeScript, you can star it, fork it, open issues, or otherwise check it out on GitHub. You may use this package yourself via use-react-router on NPM.

Senior front end engineer /

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store