Skip to content

Commit

Permalink
fix: isomorphic layout effect
Browse files Browse the repository at this point in the history
  • Loading branch information
gregberge committed Sep 26, 2019
1 parent 3b79478 commit 987f308
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions packages/core/src/colorModes.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ function useSystemMode(theme) {
return systemMode
}

const useIsomorphicLayoutEffect =
typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect

export function useColorModeState(theme, { target } = {}) {
const systemMode = useSystemMode(theme)
const defaultColorMode = getDefaultColorModeName(theme)
Expand All @@ -155,14 +158,14 @@ export function useColorModeState(theme, { target } = {}) {
}, [])

// Store mode preference
React.useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
if (manualSetRef.current) {
storage.set(mode)
}
}, [mode])

// Sync system mode
React.useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
const storedMode = storage.get()
if (storedMode) return
const targetMode = systemMode || defaultColorMode
Expand All @@ -171,7 +174,7 @@ export function useColorModeState(theme, { target } = {}) {
}, [mode, systemMode, defaultColorMode])

// Add and remove class names
React.useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
if (!customPropertiesEnabled) return undefined
const stored = storage.get()
const initial = initialColorMode !== mode
Expand Down

0 comments on commit 987f308

Please sign in to comment.