From 02becdf4491cded0f0435e880e1ad4030d500403 Mon Sep 17 00:00:00 2001
From: dan <dan.abramov@gmail.com>
Date: Thu, 18 Apr 2024 04:39:29 +0100
Subject: [Statsig] Make gate checks lazily (#3594)

---
 src/lib/statsig/statsig.tsx | 32 ++++++++++++++++++--------------
 1 file changed, 18 insertions(+), 14 deletions(-)

(limited to 'src/lib/statsig/statsig.tsx')

diff --git a/src/lib/statsig/statsig.tsx b/src/lib/statsig/statsig.tsx
index df540d79e..62dd79bb2 100644
--- a/src/lib/statsig/statsig.tsx
+++ b/src/lib/statsig/statsig.tsx
@@ -2,11 +2,7 @@ import React from 'react'
 import {Platform} from 'react-native'
 import {AppState, AppStateStatus} from 'react-native'
 import {sha256} from 'js-sha256'
-import {
-  Statsig,
-  StatsigProvider,
-  useGate as useStatsigGate,
-} from 'statsig-react-native-expo'
+import {Statsig, StatsigProvider} from 'statsig-react-native-expo'
 
 import {logger} from '#/logger'
 import {isWeb} from '#/platform/detection'
@@ -98,16 +94,24 @@ export function logEvent<E extends keyof LogEvents>(
   }
 }
 
-export function useGate(gateName: Gate): boolean {
-  const {isLoading, value} = useStatsigGate(gateName)
-  if (isLoading) {
-    // This should not happen because of waitForInitialization={true}.
-    console.error('Did not expected isLoading to ever be true.')
+export function useGate(): (gateName: Gate) => boolean {
+  const cache = React.useRef<Map<Gate, boolean>>()
+  if (cache.current === undefined) {
+    cache.current = new Map()
   }
-  // This shouldn't technically be necessary but let's get a strong
-  // guarantee that a gate value can never change while mounted.
-  const [initialValue] = React.useState(value)
-  return initialValue
+  const gate = React.useCallback((gateName: Gate): boolean => {
+    // TODO: Replace local cache with a proper session one.
+    const cachedValue = cache.current!.get(gateName)
+    if (cachedValue !== undefined) {
+      return cachedValue
+    }
+    const value = Statsig.initializeCalled()
+      ? Statsig.checkGate(gateName)
+      : false
+    cache.current!.set(gateName, value)
+    return value
+  }, [])
+  return gate
 }
 
 function toStatsigUser(did: string | undefined): StatsigUser {
-- 
cgit 1.4.1

