Skip to content

Instantly share code, notes, and snippets.

@SaadBazaz
Last active December 11, 2023 17:27
Show Gist options
  • Save SaadBazaz/ccc392508acb84e5377cd775daaaf226 to your computer and use it in GitHub Desktop.
Save SaadBazaz/ccc392508acb84e5377cd775daaaf226 to your computer and use it in GitHub Desktop.
PostHog Feature Flag custom hook for Next.js 13+
"use client"
import useFeature from "hooks/use-feature"
const App = () => {
// Example usage
const isTestFeatureEnabled = useFeature("test-feature")
if (isTestFeatureEnabled) return "hello"
return "world"
}
"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