I have this situation and I don't know why is happening..
I have a custom hook that holds a variable that I can't initialize until another function is executed.
I think it's not about a sync situation because the console.log( '..', name ) is showing the value of the variable before the execution of the useEffect(), also I put a button to manually trigger the useEffect hook (using another state variable and changing his value in the onClick function) and the value was also undefined.
export const useMagic = () => {
...
let name: string;
...
const initMagic = async () => {
...
name= 'Copperfield';
console.log('the value of the variable is:', name);
...
}
useEffect(()=> {
const loadRabbit = async () => {
console.log('The name is', name); //undefined *** HERE IS THE PROBLEM ***
}
loadRabbit();
}, [someDeps]); // I can't put name inside the dependencies because is used before being assigned. I can't initialize the variable because I need another value to create it.
}
I solved the situation using useRef on the variable and putting it in the dependency array.
But, why is this happening ? There's something that I don't know about how React manages the values of the variables..
Thanks!