Skip to content

Commit 67a0a0d

Browse files
committed
Add before unmount tracking
1 parent 95a4693 commit 67a0a0d

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/index.test.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ describe('useLog', () => {
7474
logUnmount()
7575
})
7676
expect(consoleLog).toBeCalledWith('On unmount: null')
77-
expect(consoleLog).toBeCalledTimes(6)
77+
expect(consoleLog).toBeCalledWith('Before unmount: onChange 2s')
78+
expect(consoleLog).toBeCalledTimes(7)
7879
})
7980
})

src/index.tsx

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect } from 'react'
1+
import { useEffect, useRef } from 'react'
22

33
export interface UseLogReturn {
44
log: <T>(value: T) => void
@@ -7,6 +7,13 @@ export interface UseLogReturn {
77
export const useLog = (): UseLogReturn => {
88
function log<T>(value: T): void {
99
return (() => {
10+
const isUnmounting = useRef(false)
11+
useEffect(() => {
12+
return () => {
13+
isUnmounting.current = true
14+
}
15+
}, [])
16+
1017
useEffect(() => {
1118
console.log(`On mount: ${String(value)}`)
1219

@@ -17,6 +24,12 @@ export const useLog = (): UseLogReturn => {
1724

1825
useEffect(() => {
1926
console.log(`On change: ${String(value)}`)
27+
28+
return () => {
29+
if (isUnmounting.current) {
30+
console.log(`Before unmount: ${String(value)}`)
31+
}
32+
}
2033
}, [value])
2134
})()
2235
}

0 commit comments

Comments
 (0)