Detecting unnecessarily mounted React components in a large app

Gajus Kuizinas

Frontend Engineer
React
We ran into a problem while refactoring how we load modals in our app: How do we know which pages use them and which do not?
For context, our earlier implementation simply added all possible modals to the layout and lazy-loaded them when they become necessary. However, this caused problems (it throws off bundler into thinking that layout needs those modals). So we refactored our codebase such that modals need to be explicitly added to the pages where they are going to be used. However, finding out which pages load a modal is not an easy undertaking in a large application...
I could simply add console.log() to each Modal, navigate through the app and look at the logs, but this would take a long time and it would be error prone.
I could add console.log() and run integration tests, but there is no easy way to capture those logs.
The solution was rather simple, but one that I've not had to use previously in the context of frontend development: add a beacon that registers when a modal is loaded and then run integration tests. So that's what I did.
const debugCache: Record<string, true> = {};

const debugModals = (componentName: string, pageId: string) => {
const key = componentName + ':' + pageId;

if (debugCache[key]) {
return;
}

debugCache[key] = true;

const headers = new Headers();
headers.append('Content-Type', 'application/json');

const body = { componentName, pageId };

const options = {
// eslint-disable-next-line no-restricted-properties
body: JSON.stringify(body),
headers,
method: 'POST',
mode: 'cors',
};

// @ts-expect-error throw away code
fetch('https://en101gu2pc62m.x.pipedream.net/', options);
};
I wrote a quick-and-dirty utility that utilizes RequestBin to log every time a Modal is rendered, and then I ran the integration tests and watched the request log fill up with information about the location of every component. This simple technique saved hours of debugging time and allowed to refactor code in such a way that allows to only include modals where they are necessary.
As I am done with the immediate fix, now the next step is to figure out how we can add the equivalent check to our CI/CD to ensure that no code paths are mounted to pages that never use them (or at least that are not covered by integration tests).
Partner With Gajus
View Services

More Projects by Gajus