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:
Why does it loop infinitely?
2
Answers
Add dependency array, Then it will get called only once –
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 thisuseEffect
is getting called, when you add[ ]
dependency as a parameter touseEffect
then it will act ascomponentDidMount
which get called only once.useEffect will be triggered every time the setState is set, if you do not pass the second parameter