Home > Mobile >  React Native infinite loop
React Native infinite loop

Time:10-06

I declared and initialized the variable like this:

const [user, setUser] = useState(null)

Then make a function like this:

const getUser2 = async () => {
    try {
      const user2 = await AsyncStorage.getItem('user')
      let parsed = JSON.parse(user2)
      setUser(parsed)
      console.warn('1')
    } catch(err) {}
}

Then call it like this:

useEffect(() => {
    getUser2()
    return () => getUser2()
})

The problem is when I run it, it produces an infinite loop like this: enter image description here

Why does it loop infinitely?

CodePudding user response:

Add dependency array, Then it will get called only once -

useEffect(() => {
    getUser2()
    return () => getUser2()
}, [])

Go through this reference for better understanding of useEffect - https://blog.logrocket.com/guide-to-react-useeffect-hook/

In your useEffect you haven't added any dependency array, so on each re-render this useEffect is getting called, when you add [ ] dependency as a parameter to useEffect then it will act as componentDidMount which get called only once.

CodePudding user response:

useEffect will be triggered every time the setState is set, if you do not pass the second parameter

  • Related