Skip to content

Commit

Permalink
fix(r18): useTransition hook
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuaellis committed Apr 14, 2022
1 parent 53addc3 commit b2fff6d
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 20 deletions.
2 changes: 2 additions & 0 deletions demo/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ ReactDOM.createRoot(document.getElementById('root')).render(
<App />
</React.StrictMode>
)

// ReactDOM.createRoot(document.getElementById('root')).render(<App />)
20 changes: 15 additions & 5 deletions packages/core/src/hooks/useTransition.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,24 @@ export function useTransition(
})

// Destroy all transitions on dismount.
useOnce(() => () => {
useOnce(() => {
each(usedTransitions.current!, t => {
if (t.expired) {
clearTimeout(t.expirationId!)
t.ctrl.ref?.add(t.ctrl)
const change = changes.get(t)
if (change) {
t.ctrl.start(change.payload)
}
detachRefs(t.ctrl, ref)
t.ctrl.stop(true)
})

return () => {
each(usedTransitions.current!, t => {
if (t.expired) {
clearTimeout(t.expirationId!)
}
detachRefs(t.ctrl, ref)
t.ctrl.stop(true)
})
}
})

// Keys help with reusing transitions between renders.
Expand Down
19 changes: 4 additions & 15 deletions packages/shared/src/hooks/useForceUpdate.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,13 @@
import { useState } from 'react'
import { useOnce } from './useOnce'
import { useIsMounted } from './useIsMounted'

/** Return a function that re-renders this component, if still mounted */
export function useForceUpdate() {
const update = useState<any>()[1]
const mounted = useState(makeMountedRef)[0]
useOnce(mounted.unmount)
const isMounted = useIsMounted()
return () => {
if (mounted.current) {
update({})
if (isMounted.current) {
update(Math.random())
}
}
}

function makeMountedRef() {
const mounted = {
current: true,
unmount: () => () => {
mounted.current = false
},
}
return mounted
}
15 changes: 15 additions & 0 deletions packages/shared/src/hooks/useIsMounted.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { useRef } from 'react'
import { useLayoutEffect } from './useLayoutEffect'

export const useIsMounted = () => {
const isMounted = useRef(false)
useLayoutEffect(() => {
isMounted.current = true

return () => {
isMounted.current = false
}
}, [])

return isMounted
}

0 comments on commit b2fff6d

Please sign in to comment.