Prevent infinite updates in useEffect
Solidify your knowledge of Component Lifecycle Phases by solving this problem.
Recently, Dogendar 🐶 found an API that tells a person's lucky number when you call it. So he decides to write a component DisplayLuckyNumber
that fetches his lucky number using the API and displays it. But, the catch is that the API gives back your lucky number only if you call it once. Meaning, if you call the API more than once, it'll give back unlucky numbers.
The component takes a prop fetchLuckyNumber
. It's a function that can be used to fetch lucky number from the API asynchronously i.e. it returns a Promise that resolves with the lucky number. So, it can be used like,
fetchLuckyNumber().then((luckyNumber) => { console.log(fetchLuckyNumber) })
Dogendar wrote the component but it has a bug that's leading to calling the API infinitely, every time the component rerenders and so the API first displays the lucky number but then starts displaying unlucky numbers until he closes the app!
Dogendar is asking your help to fix the bug. You need to ensure that the fetchLuckyNumber
is only called once when the component is mounted and never again if component rerenders. This will ensure that we call the API only once and show the lucky number and never receieve an unlucky number.