title: React Native's useNavigation hook inside of a custom hook?
body: <p>Im using React Navigation's <code>useNavigation</code> hook:</p>
  
  <p>In MyComponent.js: </p>
  
  <pre><code>import { useNavigation } from "@react-navigation/native";
  
  const MyComponent = () =&gt; {
      const navigation = useNavigation();
      const handleNav = () =&gt; {
          navigation.navigate("about");
      };
      return(
          &lt;TouchableOpacity onPress={handleNav}&gt;
              &lt;Text&gt;About&lt;/Text&gt;
          &lt;/TouchableOpacity&gt;
      )
  }
  </code></pre>
  
  <p>Is there a way to move this functionality to a custom hook? I tried the following: </p>
  
  <p>In useCustomNav.js: </p>
  
  <pre><code>import { useNavigation } from "@react-navigation/native";
  
  const useCustomNav = ({ to }) =&gt; {
    const navigation = useNavigation();
    navigation.navigate(to);
    return null;
  };
  
  export default useCustomNav;
  </code></pre>
  
  <p>In MyComponent.js: </p>
  
  <pre><code>import useCustomNav from './useCustomNav';
  
  const MyComponent = () =&gt; {
      const handleNav = () =&gt; {
          useCustomNav("about");
      };
      return(
          &lt;TouchableOpacity onPress={handleNav}&gt;
              &lt;Text&gt;About&lt;/Text&gt;
          &lt;/TouchableOpacity&gt;
      )
  }
  </code></pre>
  
  <p>Im getting an error:</p>
  
  <blockquote>
    <p>Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component. </p>
  </blockquote>
  
  <p>I understand that this is happening as <code>useNavigation</code> is 'hidden' within a function call but not how to fix it.</p>
  
  <p>The reason Im trying to do this is I'm sharing code between a React Native and React Native Web project but I need to do routing differently. Expo can target different platforms with different file names eg <code>useCustomNav.native.js</code> for native and <code>useCustomNav.web.js</code> for the web. So I need to have a swappable function for routing for the different platforms. I cant have the <code>useNavigation</code> hook in <code>MyComponent</code> as it's only going to be used for native, it will error for web. </p>