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
Araucanian herringOP
E.g. I want to add an event listener to
Initially, I wanted to place the code next to the call of
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.
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
In a React or Remix project, we can achieve this by placing the code next to the call of
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.@Araucanian herring <@484037068239142956>
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.
Well, but you don’t have access to the hydrateRoot call, do you?
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