-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
53addc3
commit b2fff6d
Showing
4 changed files
with
36 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |