Dmathz
Dmathz

Reputation: 57

React Native infinite loop

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?

Upvotes: 0

Views: 156

Answers (2)

Kailash
Kailash

Reputation: 877

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.

Upvotes: 2

梅花三十三
梅花三十三

Reputation: 100

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

Upvotes: 1

Related Questions