Infinite loop in useFocusEffect using AsynStorage

176 Views Asked by At

I have a component that is using useFocusEffect hook to fetch data from AsyncStorage when the router goes back to this component.

const [carNames, setCarNames] = useState([]);

useFocusEffect(() => {
  async function getCarNames() {
      const cars = await AsyncStorage.getAllKeys();
      setCarNames(cars);
  }
  getCarNames();
})

This is causing an infinite loop, the function getCarNames is called over and over again. If I comment setCarNames(cars) out the infinite loop stops, so it looks like every time the component is rendered this hook invokes the function. How to avoid this? I thought that this hook only invokes the function when route is "focused".

1

There are 1 best solutions below

0
On BEST ANSWER

I'm not sure if Expo is simply re-exporting the hook from React Navigation, or if they have rolled their own version, but this would be expected behavior when using the React Navigation useFocusEffect. Their docs note that you need to wrap the inner function in a useCallback, or else it'll redefine the inner function on every render. Try:

useFocusEffect(
  React.useCallback(() => {
    async function getCarNames() {
      const cars = await AsyncStorage.getAllKeys();
      setCarNames(cars);
    }
    getCarNames();
  }, [])
);

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