5

React navigation V6 documentation shows examples of using useCallback inside useFocusEffect. However when I use the same code, I encounter invalid-hook-call.

link: https://reactnavigation.org/docs/use-focus-effect/

example:

import { useFocusEffect } from '@react-navigation/native';

function Profile({ userId }) {
  const [user, setUser] = React.useState(null);

  useFocusEffect(
    React.useCallback(() => {
      const unsubscribe = API.subscribe(userId, user => setUser(user));

      return () => unsubscribe();
    }, [userId])
  );

  return <ProfileContent user={user} />;
}

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

There are three common reasons you might be seeing it:

  1. You might have mismatching versions of React and React DOM.
  2. You might be breaking the Rules of Hooks.
  3. You might have more than one copy of React in the same app.

Hooks can only be called inside the body of a function component, as I understand. However, why is the above example from documentation not working?

package.json

 "@react-navigation/bottom-tabs": "^6.0.9",
 "@react-navigation/native": "^6.0.6",
 "@react-navigation/stack": "^6.0.11",
 "react": "17.0.2",
 "react-native": "0.65.1",
javapedia.net
  • 2,531
  • 4
  • 25
  • 50

1 Answers1

2

I got the same problem but I removed it by removing the arrow function inside useFocusEffect(). I think this was the rule break the error was mentioning. However, I am not 100% sure about that. The error should get resolved if youre move the arrow function. Please have a look at the old and new version of my code.

Old Version

useFocusEffect(() => {
    React.useCallback(() => {
      mobxCentralStore
        .udpateFoo()
        .then(() => {})
        .catch(() => {});

      screenStore.lastTimeMsUpdateFoo;
    }, [])});

New Version

useFocusEffect(
    React.useCallback(() => {
      mobxCentralStore
        .updateFoo()
        .then(() => {})
        .catch(() => {});

      screenStore.lastTimeMsUpdateFoo;
    }, []),
  );