refactor mobile web color hydration
Replace the hydration state effect with useSyncExternalStore so the web color-scheme hook keeps its static-render fallback without triggering the set-state-in-effect lint warning.
This commit is contained in:
parent
f8f986536b
commit
df3276fc87
1 changed files with 18 additions and 10 deletions
|
|
@ -1,21 +1,29 @@
|
||||||
import { useEffect, useState } from 'react';
|
import { useSyncExternalStore } from "react"
|
||||||
import { useColorScheme as useRNColorScheme } from 'react-native';
|
import { useColorScheme as useRNColorScheme } from "react-native"
|
||||||
|
|
||||||
|
function subscribe() {
|
||||||
|
return () => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSnapshot() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
function getServerSnapshot() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* To support static rendering, this value needs to be re-calculated on the client side for web
|
* To support static rendering, this value needs to be re-calculated on the client side for web
|
||||||
*/
|
*/
|
||||||
export function useColorScheme() {
|
export function useColorScheme() {
|
||||||
const [hasHydrated, setHasHydrated] = useState(false);
|
const hasHydrated = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
|
||||||
|
|
||||||
useEffect(() => {
|
const colorScheme = useRNColorScheme()
|
||||||
setHasHydrated(true);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const colorScheme = useRNColorScheme();
|
|
||||||
|
|
||||||
if (hasHydrated) {
|
if (hasHydrated) {
|
||||||
return colorScheme;
|
return colorScheme
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'light';
|
return "light"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue