UNPKG

913 BTypeScriptView Raw
1import { nanoid } from 'nanoid/non-secure';
2import * as React from 'react';
3
4import { SingleNavigatorContext } from './EnsureSingleNavigator';
5
6/**
7 * Register a navigator in the parent context (either a navigation container or a screen).
8 * This is used to prevent multiple navigators under a single container or screen.
9 */
10export default function useRegisterNavigator() {
11 const [key] = React.useState(() => nanoid());
12 const container = React.useContext(SingleNavigatorContext);
13
14 if (container === undefined) {
15 throw new Error(
16 "Couldn't register the navigator. Have you wrapped your app with 'NavigationContainer'?\n\nThis can also happen if there are multiple copies of '@react-navigation' packages installed."
17 );
18 }
19
20 React.useEffect(() => {
21 const { register, unregister } = container;
22
23 register(key);
24
25 return () => unregister(key);
26 }, [container, key]);
27
28 return key;
29}