In a React application, you normally initialize Google Tag Manager (GTM) in the main application component’s lifecycle method, making it available throughout your application. However, since your requirement is to disable or remove GTM scripts after a specific user action (like logging in), you’ll need a conditional approach.
Unfortunately, the react-gtm-module doesn’t explicitly support unloading/removing GTM once initialized but there’s a way around. You can take advantage of the dynamic nature of javascript and React’s lifecycle methods to load/unload GTM based on the user’s authentication state.
You’ll initialize the GTM in a specific component (or page) where you need it to track whatever information required. Once the user logins, you can change the state of the component triggering a re-render and making sure it does not initialize GTM again.
Remember not to initialize GTM in the root component of your React app. Instead, initialize it at the page level components where you want the tag manager to track information. Initialize it in the componentDidMount or useEffect hook (if using functional components) based on some state (like user not logged in).
As a reminder, this approach means you must handle the initialization and potential un-initialization of GTM on every specific page level component where tracking is required. Since the GTM script is loaded asynchronously, unloading it might not be instant and there may be some lag time, during which user activities might still be tracked.
For that perfect solution removal of GTM would be a much more complex task because GTM, once loaded, creates various data layers and variables which are not easy to remove completely from the application runtime.
In case, you want to prevent any tracking after the user logs in, you can use a different approach to prevent any GTM tags from firing after login, using the GTM admin console. You can set a unique cookie at user login, and in the GTM console, create a trigger that fires on all pages where the cookie is not set. This way, once a user logs in, the cookie is set and the trigger stops firing, effectively disabling tracking. This approach also has the advantage of simplicity and will help you manage all tracking behavior directly from the GTM console, without touching the code.