From 21371081c6ee87964ddab099dce2a3ea535771e7 Mon Sep 17 00:00:00 2001
From: Eric Bailey <git@esb.lol>
Date: Mon, 11 Sep 2023 16:39:31 -0500
Subject: fix theme flashing (#1417)

* fix theme flashing

* remove memo

* use AppState listener
---
 src/lib/ThemeContext.tsx | 36 ++++++++++++++++++++++++++++--------
 1 file changed, 28 insertions(+), 8 deletions(-)

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

diff --git a/src/lib/ThemeContext.tsx b/src/lib/ThemeContext.tsx
index 2f2f268da..fe25dde54 100644
--- a/src/lib/ThemeContext.tsx
+++ b/src/lib/ThemeContext.tsx
@@ -1,5 +1,11 @@
-import React, {ReactNode, createContext, useContext, useMemo} from 'react'
-import {TextStyle, useColorScheme, ViewStyle} from 'react-native'
+import React, {ReactNode, createContext, useContext} from 'react'
+import {
+  AppState,
+  TextStyle,
+  useColorScheme,
+  ViewStyle,
+  ColorSchemeName,
+} from 'react-native'
 import {darkTheme, defaultTheme} from './themes'
 
 export type ColorScheme = 'light' | 'dark'
@@ -91,14 +97,28 @@ export const ThemeProvider: React.FC<ThemeProviderProps> = ({
   children,
 }) => {
   const colorSchemeFromRN = useColorScheme()
+  const [nativeColorScheme, setNativeColorScheme] =
+    React.useState<ColorSchemeName>(colorSchemeFromRN)
 
-  // if theme is 'system', use the device's configured color scheme
-  let colorScheme = theme === 'system' ? colorSchemeFromRN : theme
+  React.useEffect(() => {
+    const subscription = AppState.addEventListener('change', state => {
+      const isActive = state === 'active'
 
-  const value = useMemo(
-    () => (colorScheme === 'dark' ? darkTheme : defaultTheme),
-    [colorScheme],
-  )
+      if (!isActive) return
+
+      setNativeColorScheme(colorSchemeFromRN)
+    })
+    return () => subscription.remove()
+  }, [colorSchemeFromRN])
+
+  const value =
+    theme === 'system'
+      ? nativeColorScheme === 'dark'
+        ? darkTheme
+        : defaultTheme
+      : theme === 'dark'
+      ? darkTheme
+      : defaultTheme
 
   return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
 }
-- 
cgit 1.4.1

