Skip to content

Commit b2fff6d

Browse files
committed
fix(r18): useTransition hook
1 parent 53addc3 commit b2fff6d

File tree

4 files changed

+36
-20
lines changed

4 files changed

+36
-20
lines changed

demo/src/index.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,5 @@ ReactDOM.createRoot(document.getElementById('root')).render(
88
<App />
99
</React.StrictMode>
1010
)
11+
12+
// ReactDOM.createRoot(document.getElementById('root')).render(<App />)

packages/core/src/hooks/useTransition.tsx

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -103,14 +103,24 @@ export function useTransition(
103103
})
104104

105105
// Destroy all transitions on dismount.
106-
useOnce(() => () => {
106+
useOnce(() => {
107107
each(usedTransitions.current!, t => {
108-
if (t.expired) {
109-
clearTimeout(t.expirationId!)
108+
t.ctrl.ref?.add(t.ctrl)
109+
const change = changes.get(t)
110+
if (change) {
111+
t.ctrl.start(change.payload)
110112
}
111-
detachRefs(t.ctrl, ref)
112-
t.ctrl.stop(true)
113113
})
114+
115+
return () => {
116+
each(usedTransitions.current!, t => {
117+
if (t.expired) {
118+
clearTimeout(t.expirationId!)
119+
}
120+
detachRefs(t.ctrl, ref)
121+
t.ctrl.stop(true)
122+
})
123+
}
114124
})
115125

116126
// Keys help with reusing transitions between renders.
Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,13 @@
11
import { useState } from 'react'
2-
import { useOnce } from './useOnce'
2+
import { useIsMounted } from './useIsMounted'
33

44
/** Return a function that re-renders this component, if still mounted */
55
export function useForceUpdate() {
66
const update = useState<any>()[1]
7-
const mounted = useState(makeMountedRef)[0]
8-
useOnce(mounted.unmount)
7+
const isMounted = useIsMounted()
98
return () => {
10-
if (mounted.current) {
11-
update({})
9+
if (isMounted.current) {
10+
update(Math.random())
1211
}
1312
}
1413
}
15-
16-
function makeMountedRef() {
17-
const mounted = {
18-
current: true,
19-
unmount: () => () => {
20-
mounted.current = false
21-
},
22-
}
23-
return mounted
24-
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { useRef } from 'react'
2+
import { useLayoutEffect } from './useLayoutEffect'
3+
4+
export const useIsMounted = () => {
5+
const isMounted = useRef(false)
6+
useLayoutEffect(() => {
7+
isMounted.current = true
8+
9+
return () => {
10+
isMounted.current = false
11+
}
12+
}, [])
13+
14+
return isMounted
15+
}

0 commit comments

Comments
 (0)