How to convert withRouter to a React hook

Charles Stover
6 min readOct 30, 2018

One of the greatest benefits of React Hooks in the new v16.7 is the removal of the reliance on higher-order components. While in the process of migrating my class states to functional hooks, I was giddy at the opportunity to port my with-router higher-order component to a hook as well. I have been using this custom implementation to re-render my components on route change. react-router's built-in withRouter HOC does not re-render components on route change, and it is a difficult issue to work around.

This article should serve as a tutorial for implementing a React hook with pub-sub functionality. Pub-sub, short for “publish-subscribe,” is a programming methodology wherein a set of subscription processes become notified when an update is published. In short, when the location changes (the published event), I want to re-render my component (the listener subscription).

The final product requires React Router v4.4 or greater, as previous versions of React Router did not expose the Router Context, which we are using to listen to location changes. If the latest version of React Router is not accessible to you, you can listen to the window history state as an alternative. I opted to use the same “single source of truth” that react-router uses, insuring that my states are always in sync.

--

--

Charles Stover
Charles Stover

Written by Charles Stover

Staff+ front end engineer | Tech lead | Architect | quisi.do

Responses (6)