I’m new to React (and coding in general, as a student).
But I had a (hopefully basic!!) query –
Say I have a React component, and it has the following ref:
const productionMode = useRef<boolean>(true);
lets say I have a function within this component which (simplistic example), says:
if (productionMode) {
callToProdEnvironment();
}
But my concern is, say I have some async function which changes the value of productionMode to false right after it passes the if.
This would mean that I would be making a call to my production environment, which could potentially be very problematic.
Now. I could totally add a check to callToProdEnvironment which checks once again that productionMode is true, but this seems a little repetitive. Maybe it totally isn’t a bad thing though. Please let me know.
But this one really makes me scratch my head:
Take this example:
const aRef = useRef<MyCustomObject | undefined>(myObj);
if (aRef.current) {
console.log(aRef.current.aProperty);
}
if (aRef.current) passes.. but due to an async operation that changes aRef’s value (to undefined), then accessing .aProperty on an undefined would not work! And I can’t exactly add extra protection there.
I saw a suggestion about doing something like:
const aRef = useRef<MyCustomObject | undefined>(myObj);
const current = aRef.current;
if (current) {
console.log(current.aProperty);
}
But to my mind this is an even staler version of aRef.current…
I can’t really get my head around this, and I’m aware it’s probably a very fundamental concern about race-conditions/the issues with async executions. But I am new to all of this, like I say, and I just wanted a little bit of perspective! I’ve spent hours trying to make sense of it. I feel a bit stupid!