Dispatch redux actions with history.listen on location change in React Router v5

history listener with useEffect hook

Vladimir Strilets | Web Developer
1 min readAug 25, 2020

Let’s assume you need to call (dispatch) some redux action every time the web browser history location (pathname) is changed.

For React Router v4 I found this solution using a custom history, set the listener like this (source) and pass it to <Router /> component.

But, I’m using React Router v5.2 and looks like it prefers to use <BrowserRouter /> instead of <Router />.

Ok, no problem, let’s make some extra component, HistoryListener.js

And now my App.js looks like:

// App.js// ... importsconst App = () => (
<Provider store={store}>
<BrowserRouter>
<HistoryListener> // <-- here we added our component
<AppRoutes />
</HistoryListener>
</BrowserRouter>
</Provider>
);

Now, when we init our web application, the loader <p>Loading...</p> will be rendered, then someAction() and setIsFirstRender(false) will be called. So, we have dispatched the action we needed on the first render and now we return the children component <AppRoutes /> , but also it was created a history listener that dispatches the action on every history change.

I am pretty sure you could also use async actions with redux-thunk inside the useEffect() in HistoryListener.js.

Clap if it was useful :)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response