Guaranteed
Guaranteed

Reputation: 153

Is there a proper way to use useNavigation() hook with useEffect() dependencies?

I'm trying to interact with react-navigation using useNavigation() hook in response to a callback I'm registering in useEffect(). The linter is warning me that useEffect() has a missing dependency. If I add the navigation hook as a dependency, the effect continuously runs. I'm trying to avoid this and wondering if there is a correct way other than ignoring the linter error.

Providing no dependency array results in the same behavior where the effect continuously fires.

This may be an underlying issue with how the useNavigation() hook from react-navigation-hooks package works.

function MyComponent() {
    const navigation = useNavigation();

    useEffect(() => {
        navigation.navigate('Home');
    }, []);
}

Results in:

React Hook useEffect has a missing dependency: 'navigation'. Either include it or remove the dependency array.

Upvotes: 8

Views: 16175

Answers (2)

theRolk
theRolk

Reputation: 17

I believe the error message is clear, you are missing the useEffect dependency:

function MyComponent() {
    const navigation = useNavigation();

    useEffect(() => {
        if (!navigation) return; // <-- this will avoid any undefined or null calls
        navigation.navigate('Home');
    }, [navigation]); // <-- this dependency
}

Upvotes: 0

Bennett Dams
Bennett Dams

Reputation: 7033

Just an opinionated guess: It's more a question regarding your "architecture".

For example: Wouldn't it make more sense for the custom useNavigation hook to return a function that can be called by the consumer of the hook instead of an object with all it's functionality?

Here is an example:

const useNavigation = () => {
  const [routes, setRoutes] = useState(null);
  ...

  const navigate = (destination: string) => {
    console.log("navigated to ", destination);
  };

  return { navigate, routes };
};

function App() {
  const { navigate } = useNavigation();

  return (
    <div className="App">
      <h1>Parent</h1>
      <button onClick={() => navigate("Home")}>Navigate me!</button>
    </div>
  );
}

Working Codesandbox: https://codesandbox.io/s/usenavigation-95kql


If you nevertheless want to keep this "architecture", you could use a useRef hook like so:

const navigation = useRef(useNavigation());

useEffect(() => {
  navigation.current.navigate("Home");
}, []);

Upvotes: 8

Related Questions