Skip to content

Commit

Permalink
Prevent automatic batching updates in ThemeProvider to ensure client …
Browse files Browse the repository at this point in the history
…use right colorMode (#2732)

* Prevent automatic batching updates in ThemeProvider to ensure client use right colorMode

* Add changeset

Co-authored-by: Josh Black <joshblack@github.com>
  • Loading branch information
renbaoshuo and joshblack committed Jan 17, 2023
1 parent 51f51df commit 3f70b2e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/blue-ads-hunt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/react': patch
---

Prevent automatic batching updates in ThemeProvider to ensure client use right colorMode
10 changes: 8 additions & 2 deletions src/ThemeProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from 'react'
import ReactDOM from 'react-dom'
import {ThemeProvider as SCThemeProvider} from 'styled-components'
import defaultTheme from './theme'
import deepmerge from 'deepmerge'
Expand Down Expand Up @@ -83,8 +84,13 @@ export const ThemeProvider: React.FC<React.PropsWithChildren<ThemeProviderProps>
// if the resolved color mode passed on from the server is not the resolved color mode on client, change it!
if (resolvedColorModePassthrough.current !== resolvedColorModeOnClient) {
window.setTimeout(() => {
// override colorMode to whatever is resolved on the client to get a re-render
setColorMode(resolvedColorModeOnClient)
// use ReactDOM.flushSync to prevent automatic batching of state updates since React 18
// ref: https://github.com/reactwg/react-18/discussions/21
ReactDOM.flushSync(() => {
// override colorMode to whatever is resolved on the client to get a re-render
setColorMode(resolvedColorModeOnClient)
})

// immediately after that, set the colorMode to what the user passed to respond to system color mode changes
setColorMode(colorMode)
})
Expand Down

0 comments on commit 3f70b2e

Please sign in to comment.