Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(useContextBridge): return a stable context bridge #11

Merged
merged 2 commits into from
Sep 22, 2022

Conversation

CodyJasonBennett
Copy link
Member

@CodyJasonBennett CodyJasonBennett commented Sep 22, 2022

Prevents React from remounting roots whenever context updates from scratch, emulating StrictMode.

import * as React from 'react'
import * as ReactDOM from 'react-dom/client'
import { render } from 'react-nil'
import { useContextBridge, FiberProvider } from 'its-fine'

const Context = React.createContext(null)

// would log mount, unmount, mount; should log mount
function Inner() {
  React.useEffect(() => (console.log('mount'), () => console.log('unmount')), [])
  return null
}

function Canvas(props) {
  const Bridge = useContextBridge()
  render(<Bridge>{props.children}</Bridge>)
}

// skip 2 browser paints
const flush = (cb, raf = requestAnimationFrame) => raf(() => raf(() => raf(() => raf(() => cb()))))

function Outer(props) {
  const [value, setValue] = React.useState(() => true)
  React.useEffect(() => void flush(() => (setValue(false), flush(() => setValue(true)))), [])
  return <Context.Provider value={value}>{props.children}</Context.Provider>
}

ReactDOM.createRoot(window.root).render(
  <FiberProvider>
    <Outer>
      <Canvas>
        <Inner />
      </Canvas>
    </Outer>
  </FiberProvider>,
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant