Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save karol-majewski/c1045713984ba58d262f19c38aac46d8 to your computer and use it in GitHub Desktop.
Save karol-majewski/c1045713984ba58d262f19c38aac46d8 to your computer and use it in GitHub Desktop.
A User Timing middleware for Redux to create performance markers for dispatched actions. Remade with TypeScript (Redux v.4).
import { AnyAction, Middleware } from 'redux';
export const userTimingMiddleware: Middleware = () => {
return next => {
return <A extends AnyAction>(action: A): A => {
if (performance.mark === undefined) {
return next(action);
}
performance.mark(`${action.type}_start`);
const result = next(action);
performance.mark(`${action.type}_end`);
performance.measure(
`${action.type}`,
`${action.type}_start`,
`${action.type}_end`,
);
return result;
};
};
};
@karol-majewski
Copy link
Author

Alternative approach:

import { AnyAction, Dispatch, Middleware } from 'redux';

const EMPTY_MIDDLEWARE: Middleware = () => next => action => next(action);

export const userTimingMiddleware: Middleware = (() => {
  if ('performance' in window) {
    return () => (next: Dispatch<AnyAction>) => {
      return <A extends AnyAction>(action: A): A => {
        performance.mark(`${action.type}_start`);
        const result = next(action);
        performance.mark(`${action.type}_end`);

        performance.measure(
          `${action.type}`,
          `${action.type}_start`,
          `${action.type}_end`,
        );

        return result;
      };
    };
  }

  return EMPTY_MIDDLEWARE;
})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment