Google Tag Manager Hook for React

Google Tag Manager Hook for React

Google Tag Manager is a powerful tool from Google for managing tags (like cookies, pixels, scripts, etc...) on your app/website from a single entry point and without editing your codebase!

The GTM is an awesome tool for marketers and developers for adding external libs, handling events and analytics tags without affecting the codebase, and, above all, give to the marketing team some working autonomy without deploying a new version of the app/website.


Why I wrote this Hook?

Basically, because we are in the Hook era and, at the moment of writing, there was not any hook to handle it.


The Hook will inject the GTM scripts into the document and you don't have to edit your index.html anymore.

You can also pass as parameters a custom dataLayer name (it will replace the default dataLayer) and custom values/variables to it.

There is also a method to send custom data/events to the GTM (is a wrapper for the dataLayer.push())

Example Snippets

Basic/Default usage

import { useEffect } from 'react'
import useGTM from '@elgorditosalsero/react-gtm-hook'

const App = () => {
  const { init } = useGTM()

  useEffect(() => init({ id: 'GTM-ID' }), [])

  return <p>My awesome app</p>

Send event (after initialization)

const MyAwesomeComp = () => {
  const { sendDataToGTM } = useGTM()

  const handleClick = () => sendDataToGTM({ 
    event: 'awesomeButtonClicked', 
    value: 'imAwesome' 

  return (
      <p>My Awesome Comp</p>
      <button onClick={handleClick}>My Awesome Button</button>

So, what do you think? Will you try it?

If you think would be useful an article with more examples and/or screenshots also from the Tag Manager, let me know in the discussion section

Pull Request, contributions and issue are welcome!

If this Hook was useful to you and you like it, please add a reaction and/or leave a comment and star on GitHub!