1 | import * as React from 'react';
|
2 | import { useState } from 'react';
|
3 | import useNavigation from './useNavigation';
|
4 | /**
|
5 | * Hook to get the current focus state of the screen. Returns a `true` if screen is focused, otherwise `false`.
|
6 | * This can be used if a component needs to render something based on the focus state.
|
7 | */
|
8 |
|
9 | export default function useIsFocused() {
|
10 | const navigation = useNavigation();
|
11 | const [isFocused, setIsFocused] = useState(navigation.isFocused);
|
12 | const valueToReturn = navigation.isFocused();
|
13 |
|
14 | if (isFocused !== valueToReturn) {
|
15 | // If the value has changed since the last render, we need to update it.
|
16 | // This could happen if we missed an update from the event listeners during re-render.
|
17 | // React will process this update immediately, so the old subscription value won't be committed.
|
18 | // It is still nice to avoid returning a mismatched value though, so let's override the return value.
|
19 | // This is the same logic as in https://github.com/facebook/react/tree/master/packages/use-subscription
|
20 | setIsFocused(valueToReturn);
|
21 | }
|
22 |
|
23 | React.useEffect(() => {
|
24 | const unsubscribeFocus = navigation.addListener('focus', () => setIsFocused(true));
|
25 | const unsubscribeBlur = navigation.addListener('blur', () => setIsFocused(false));
|
26 | return () => {
|
27 | unsubscribeFocus();
|
28 | unsubscribeBlur();
|
29 | };
|
30 | }, [navigation]);
|
31 | React.useDebugValue(valueToReturn);
|
32 | return valueToReturn;
|
33 | }
|
34 | //# sourceMappingURL=useIsFocused.js.map |
\ | No newline at end of file |