Skip to content

Commit

Permalink
Merge pull request #2362 from Agenta-AI/AGE-1464/implement-useIsomorp…
Browse files Browse the repository at this point in the history
…hicLayoutEffect-to-prevent-using-useLayoutEffect-on-server

(frontend)[AGE-1464]: implement useIsomorphicLayoutEffect hook to prevent using useLayoutEffect on server
  • Loading branch information
mmabrouk authored Dec 11, 2024
2 parents bebc810 + f65f493 commit 3483f08
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
8 changes: 8 additions & 0 deletions agenta-web/src/hooks/useIsomorphicLayoutEffect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import {useLayoutEffect, useEffect} from "react"

// useIsomorphicLayoutEffect is a custom hook that uses useLayoutEffect on the client-side
// (when window is defined) and useEffect on the server-side (when window is undefined).
// This ensures that the code runs correctly in both client-side and server-side environments.
const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect

export default useIsomorphicLayoutEffect
5 changes: 3 additions & 2 deletions agenta-web/src/hooks/usePostHogAg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {useLayoutEffect} from "react"
import {isDemo, generateOrRetrieveDistinctId} from "@/lib/helpers/utils"
import {usePostHog} from "posthog-js/react"
import {useProfileData} from "@/contexts/profile.context"
import useIsomorphicLayoutEffect from "./useIsomorphicLayoutEffect"

export const usePostHogAg = () => {
const trackingEnabled = process.env.NEXT_PUBLIC_TELEMETRY_TRACKING_ENABLED === "true"
Expand All @@ -23,11 +24,11 @@ export const usePostHogAg = () => {
}
}

useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
if (!trackingEnabled) posthog.opt_out_capturing()
}, [trackingEnabled])

useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
if (posthog.get_distinct_id() !== _id) identify()
}, [user?.id])

Expand Down

0 comments on commit 3483f08

Please sign in to comment.