UNPKG

1.05 kBJavaScriptView Raw
1import * as React from 'react';
2import useNavigation from './useNavigation';
3
4/**
5 * Hook to get a value from the current navigation state using a selector.
6 *
7 * @param selector Selector function to get a value from the state.
8 */
9export default function useNavigationState(selector) {
10 const navigation = useNavigation(); // We don't care about the state value, we run the selector again at the end
11 // The state is only to make sure that there's a re-render when we have a new value
12
13 const [, setResult] = React.useState(() => selector(navigation.getState())); // We store the selector in a ref to avoid re-subscribing listeners every render
14
15 const selectorRef = React.useRef(selector);
16 React.useEffect(() => {
17 selectorRef.current = selector;
18 });
19 React.useEffect(() => {
20 const unsubscribe = navigation.addListener('state', e => {
21 setResult(selectorRef.current(e.data.state));
22 });
23 return unsubscribe;
24 }, [navigation]);
25 return selector(navigation.getState());
26}
27//# sourceMappingURL=useNavigationState.js.map
\No newline at end of file