Skip to content

Instantly share code, notes, and snippets.

@todd-elvers
Last active September 2, 2022 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save todd-elvers/28185a3b3e4115f275e86dfa6b831893 to your computer and use it in GitHub Desktop.
Save todd-elvers/28185a3b3e4115f275e86dfa6b831893 to your computer and use it in GitHub Desktop.
Deep link handling via React Native hooks
// Note: this behavior requires deep linking to be enabled on your React Native app
// https://reactnative.dev/docs/linking
type DeepLinkHandlerOptions = {
/** Determines whether or not we should call 'handleDeepLink' for a given link */
canHandleLink?: (url: string | null) => boolean;
handleDeepLink: (url: string | null) => void | Promise<void>;
};
/** Captures & handles a deep link */
export const useDeepLinkHandler = ({ canHandleLink = () => true, handleDeepLink }: DeepLinkHandlerOptions) => {
const { deepLink, clearDeepLink } = useDeepLink(canHandleLink);
React.useEffect(() => {
if (deepLink === null) return;
// Workaround for iOS specific behavior where something in the event loop
// steps on our logic and prevents our `handleDeepLink` from being called.
const timeout = setTimeout(async () => {
await handleDeepLink(deepLink);
clearDeepLink();
}, 500);
return () => {
clearTimeout(timeout);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [clearDeepLink, deepLink]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment