skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. useEffect will be triggered every time the setState is set, if you do not pass the second parameter

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search