Tuesday, September 6, 2022

the dataLayer, and using local storage for cross-tab communication

 Just the other week I started looking more closely at the "dataLayer" - it's a standard variable off of window that Google Analytics uses to let processes record analytics events.

It seems like a strange way to do an API, especially since the data doesn't need to have identical structures, and it's just a big array like object you push on to. But it seems to be kinda standard in the industry thanks to the prevalence of Google Analytics.

In other learnings, I was impressed by the results my company was getting using localStorage to communicate some state across tabs/windows, in React the setup was something like 

  useEffect(() => {

    updateFromLocalStorageData();

    const storageListener = (e: StorageEvent) => {

      if (e.key === KEY_FOR_DATA) {

        updateFromLocalStorageData();

      }

    };

    window.addEventListener('storage', storageListener);

    // deregister event listener on re-render

    return () => {

      window.removeEventListener('storage', storageListener);

    };

  }, []);


No comments:

Post a Comment