Fetching data from an API and putting them inside an array but it works differently in browser/IDE?
It's React.
Something weird happens. When I reload directly from the browser, it still logs an empty array, but when I save the file from VSCode, it displays the array just like I wanted.
2 Replies
try putting api url in separate variable, and then use it as dependency in useEffect
Hi guys I'm back with the explanation as why this is happening.
It's not that states don't update "immediately" it's that there's a big confusion about what a re-render or state update is. React is not doing what you think it's doing
Take a look at a very basic state example like this:
the
num
variable is a constant number which cannot be reassigned, similar to if it was declared like this:
there's nothing any framework or anything in the language could do to update that num
from a 0 to a 1. It's a constant number and can never change, this is true for all state variables. So how does that number change when you call setNum
? Well, it doesn't. Calling that setter tells React to run your function again, but this time it will give your function a value of 1 instead of 0.
The state doesn't get mutated. You schedule your component to be called/rendered again. But not only that. There's no way something like this could EVER work
There's nothing javascript could do to make that second console.log return anything other than 0 if num
is just a normal number. I think understanding that helps realize why and how react works the way it does.
now, to this actual behaviour, the HMR (hot module reload) from saving is able to run the component again without unmounting it
while, in the browser, you get a full reload of the page, completely remounting the component