Skip to content

Instantly share code, notes, and snippets.

@asif-simform
Forked from perlow/SuspenseRouter.tsx
Created December 29, 2023 11:10
Show Gist options
  • Save asif-simform/18174bfaaae1e15831d68d2ec48aa039 to your computer and use it in GitHub Desktop.
Save asif-simform/18174bfaaae1e15831d68d2ec48aa039 to your computer and use it in GitHub Desktop.
import { useLayoutEffect, useRef, useState, useTransition } from 'react'
import { Router } from 'react-router-dom'
import { BrowserHistory, createBrowserHistory, Update } from 'history'
export interface BrowserRouterProps {
basename?: string
children?: React.ReactNode
window?: Window
}
export function SuspenseRouter({ basename, children, window }: BrowserRouterProps) {
let historyRef = useRef<BrowserHistory>()
const [isPending, startTransition] = useTransition()
if (historyRef.current == null) {
//const history = createBrowserHistory(startTransition, { window });
historyRef.current = createBrowserHistory({ window })
}
let history = historyRef.current
let [state, setState] = useState({
action: history.action,
location: history.location,
})
function setStateAsync(update: Update) {
startTransition(() => {
setState(update)
})
}
useLayoutEffect(() => history.listen(setStateAsync), [history])
return (
<Router
basename={basename}
children={children}
location={state.location}
navigationType={state.action}
navigator={history}
/>
)
}
export default SuspenseRouter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment