Last active
December 11, 2023 17:27
-
-
Save SaadBazaz/ccc392508acb84e5377cd775daaaf226 to your computer and use it in GitHub Desktop.
PostHog Feature Flag custom hook for Next.js 13+
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use client" | |
import useFeature from "hooks/use-feature" | |
const App = () => { | |
// Example usage | |
const isTestFeatureEnabled = useFeature("test-feature") | |
if (isTestFeatureEnabled) return "hello" | |
return "world" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use client" | |
/* | |
This is a snippet which wraps PostHog's feature flags, to make it super easy for devs to have non-flickering feature | |
flags. Based on the documentation at PostHog: https://posthog.com/tutorials/nextjs-bootstrap-flags#bootstrapping-feature-flags | |
Author: Saad Bazaz | |
*/ | |
import { useEffect, useState } from "react" | |
import { usePostHog } from "posthog-js/react" | |
export function useFeature(name: string) { | |
const posthog = usePostHog() | |
const [flag, setFlag] = useState( | |
typeof window !== "undefined" ? posthog.isFeatureEnabled(name) : undefined | |
) | |
useEffect(() => { | |
if (typeof window !== "undefined") { | |
const ph_flag = posthog.isFeatureEnabled(name) | |
if (typeof ph_flag !== "undefined") { | |
setFlag(ph_flag) | |
} | |
} | |
}, [name, posthog]) | |
return flag | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment