title: How to prevent script from loading multiple times with react?
body: <p>I have a chat feature in my app and very infrequently the chat box loads twice when reloading the page. Probably something do to with some weird react re-rendering. I would like for something to check if the script has been executed already and if so don't do it again.</p>
  <p>Here is my relevant code</p>
  <pre><code> import { useEffect, useState, useRef } from 'react';
   import { useDebouncedCallback } from 'use-debounce';
  
  const debounceLoading = useDebouncedCallback((e) =&gt; {
          const firstLoad = useRef(true);
          loadScript();
          setup();
      }, 2000);
  
      useEffect(() =&gt; {
          if (firstLoad.current){
              firstLoad.current = false;
              return;
          }
          debounceLoading();
      }, []);
  
      useEffect(() =&gt; {
          if (open) {
              setWrapperClass('open');
              setButtonIcon('/images/.svg');
          } else {
              setWrapperClass('closed');
              setButtonIcon('/images/.svg');
          }
          }, [open]);
      
          const loadScript = () =&gt; {...........}
  
  return (
          &lt;div id=&quot;wrapper&quot; className={wrapperClass}&gt;
              &lt;div onClick={toggleChat} className=&quot;button&quot;&gt;
                  &lt;img src={buttonIcon} alt=&quot;Chat icon&quot; /&gt;
                  Chat
              &lt;/div&gt;
              &lt;div id=&quot;box-container&quot;&gt;&lt;/div&gt;
          &lt;/div&gt;
      );
  }
  </code></pre>
  <p>I have looked at <a href="https://stackoverflow.com/questions/9521298/verify-external-script-is-loaded/9521360">Verify External Script Is Loaded</a> and <a href="https://medium.com/anna-coding/the-way-to-check-if-its-the-first-time-for-useeffect-function-is-being-run-in-react-hooks-170520554067" rel="nofollow noreferrer">https://medium.com/anna-coding/the-way-to-check-if-its-the-first-time-for-useeffect-function-is-being-run-in-react-hooks-170520554067</a>. I also understand that this will not be a reproducible question and I'm well aware of that but any help would be appreciated.</p>
  <p>My current code is giving me errors because the useRef hook can't be called inside a callback. Does anyone know the best way to fix my issue?</p>