Next.js Discord

Discord Forum

How should I run code unrelated to React on the client side in a Next.js project?

Unanswered
Araucanian herring posted this in #help-forum
Open in Discord
Araucanian herringOP
E.g. I want to add an event listener to window to do something unrelated to React.

Initially, I wanted to place the code next to the call of hydrateRoot function, but it does not exist in Next.js project.

I referred to Sentry's Next.js SDK, which is implemented by webpack plugin. I think writing a plugin is too cumbersome for me.

I am currently in a file with 'use client' and a component and use an if statement to determine whether it is currently on the client side to do what I want. However, I don't think this is best practice.

6 Replies

Araucanian herringOP
@joulev
It is feasible to run the code in useEffect. However, I don't think using useEffect is necessary.

In a React or Remix project, we can achieve this by placing the code next to the call of createRoot or hydrateRoot function so that won't mix non-React related code with React component code.
Schneider’s Smooth-fronted Caiman
for example load a client-side js library: jQuery
Then, if(window) then execute ur code (with "use client")
if your library like jQuery is also defined under window, u can just use client with window.$ and it works