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