React Navigation RangeError: Maximum call stack size exceeded (native stack depth)

Viewed 809

So I have a screen where I want the user to stay. If he want's to leave I want him to go to a specific screen. If I do it like this:

  useEffect(() => {
    navigation.addListener("beforeRemove", (e) => {
      e.preventDefault()
      navigation.popToTop()
    })
  }, [navigation])

I get this error: RangeError: Maximum call stack size exceeded (native stack depth)

Even if I change navigation.popToTop() to something else (e.g. navigation.navigate("Account")) I'll get the same error :/

1 Answers

The final array in your code is the useEffect "dependencies array", meaning the useEffect will run whenever anything in that array changes. Adding the listener to the navigation object changes the object, so you're either adding an infinite number of listeners, or replacing the existing one in a loop (I'm not sure how navigation.addListener is implemented).

You need to do one of the following:

  • check that the listener exists in this code block and only add if it doesn't
  • make sure this adding code only executes once
Related