Next.js Discord

Discord Forum

Running third party scripts on page load

Unanswered
Snail Kite posted this in #help-forum
Open in Discord
Snail KiteOP
I suspect this is a common question, but I have to ask. What's the intended method of running a client-side JS script a single time when a user lands on a route?

I can think of a few "workarounds" but they kinda go against my understanding of good React behavior such as rendering with side effects or omitting dependencies from a useEffect.

With the Next App Router, has anything changed with this or is it still purely a React question?

To be more specific about my use case, I need to integrate a third party JS SDK that needs to first load the JS, then link to a div and run an init function. Running the init multiple times causes issues. There's no proper cleanup function. As such, it's awkward to put it in a useEffect because I also need to use refs to bypass the StrictMode double render.

Any suggestions?

Is this actually an acceptable solution? It feels flaky to me.
"use client"

export default function Page() {
  const loaded = useRef(false);

  useEffect(() => {
    if (loaded.current) return;

    const sdk = new ExternalDep("some-id", {
      // some options which may include search params
    });
    sdk.init();

    loaded.current = true;
  }, []); // deps kinda don't matter since the ref prevents re-renders

  return <div id="some-id" />
}


Alternative workaround I thought of but is essentially the same (and goes against the "render side-effects" idea):

"use client"

export default function Page() {
  const loaded = useRef(false);

  if (!loaded.current) {
    const sdk = new ExternalDep("some-id", {
      // options
    });
    sdk.init();
    loaded.current = true;
  }

  return <div id="some-id" />
}

0 Replies