forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 0
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
3af5702
commit 52ce458
Showing
2 changed files
with
40 additions
and
5 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import type {NavigationState} from '@react-navigation/routers'; | ||
import {useEffect, useRef, useState} from 'react'; | ||
import navigationRef from '@libs/Navigation/navigationRef'; | ||
|
||
type Selector<T> = (state: NavigationState) => T; | ||
|
||
/** | ||
* Hook to get a value from the current root navigation state using a selector. | ||
* | ||
* @param selector Selector function to get a value from the state. | ||
*/ | ||
function useRootNavigationState<T>(selector: Selector<T>): T { | ||
const [result, setResult] = useState(() => selector(navigationRef.getRootState())); | ||
|
||
// We store the selector in a ref to avoid re-subscribing listeners every render | ||
const selectorRef = useRef(selector); | ||
|
||
useEffect(() => { | ||
selectorRef.current = selector; | ||
}); | ||
|
||
useEffect(() => { | ||
const unsubscribe = navigationRef.addListener('state', (e) => { | ||
setResult(selectorRef.current(e.data.state as NavigationState)); | ||
}); | ||
|
||
return unsubscribe; | ||
}, []); | ||
|
||
return result; | ||
} | ||
|
||
export default useRootNavigationState; |