Using Redux Middleware for simpler analytics and event tracking
Tracking events across your application can sometimes be a pain. Whether they are Google Analytics, Sentry errors, or BigQuery tracking, the practice I’ve seen many times is to place trackThisEvent(..args) calls all around the code. This isn’t a terrible solution, especially in smaller codebases. But it can have issues when something changes with the trackThisEvent definition, or if you need to pass in more data into each call like userId or some other arbitrary value, you’ll be stuck going through 100’s of files to make updates.
Use Redux Middleware
The great thing about using redux is that all of your actions are defined with your reducers, which are then available to the entire application. Whenever an action is dispatched, your combined store is updated. You probably have a setup similar to this:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import AppContainer from 'components/app-container';
import { createStore, combineReducers } from 'redux';
import * as reducers from 'store/ducks/index';const rootReducer = {
...reducers,
// probably more reducers, like from the router
};const store = createStore(combineReducers(rootReducer));ReactDOM.render(
<Provider store={store}>
<AppContainer></AppContainer>
</Provider>,
document.getElementById('root')
);That store object has your entire combined state. Before your changes reach the reducer and become available to the store, they can go through Middleware for any transformations you need.
From Redux (https://redux.js.org/advanced/middleware) —
It provides a third-party extension point between dispatching an action, and the moment it reaches the reducer. People use Redux middleware for logging, crash reporting, talking to an asynchronous API, routing, and more.
Here’s what a simple middleware function looks like for tracking a page view event:
