forked from react-hook-form/documentation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-browser.js
43 lines (35 loc) · 1.18 KB
/
gatsby-browser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import * as React from "react"
import withLittleStateMachine from "./with-little-state-machine"
import { useStateMachine } from "little-state-machine"
export const wrapRootElement = withLittleStateMachine
export const onServiceWorkerUpdateReady = () => {
window.location.reload()
}
const forceUpdate = (state, payload) => {
return {
...state,
setting: {
...state.setting,
...payload,
},
}
}
export const wrapPageElement = ({ element }) => {
const { actions, state } = useStateMachine({ forceUpdate })
React.useEffect(() => {
if (!state?.setting?.lightMode) {
return
}
const lightMode = !state?.setting?.lightMode
// NOTE: Global state on SSR and CSR cannot be synced when using
// storage type window.localStorage of little-state-machine.
// If light mode is applied on browser, SSR still renders dark mode when opening new tab,
// enable dark mode to sync with SSR HTML response then re-apply light mode after first rendering
actions.forceUpdate({ lightMode })
// Restore selected state of light mode
setTimeout(() => {
actions.forceUpdate({ lightMode: !lightMode })
}, 200)
}, [])
return <>{element}</>
}