I've been doing some React crash course and got in a lot of problems. To start with,
observer.current.observe(ElemenentIGotWithRef.current)
wasn't working in useEffect, because for some reasons the current value wasn't set at the first render.
useEffect(()=>{
console.log(ElemenentIGotWithRef)
}, [])
console.log of my ElemenentIGotWithRef:

I solved it with
useEffect(()=>{
if (ElemenentIGotWithRef.current)
observer.current.observe(ElemenentIGotWithRef.current);
return (()=>{
observer.current.disconnect();
})
}, [ElemenentIGotWithRef.current])
But now I am stuck with another function, which doesn't work normally because of my crutch / my unproper useEffect work.
How could I make ref set value at the first render?
Usually the element is ready before
useEffectis called. However, in certain situations (conditional rendering for example), the element is not ready, and therefis not set immediately. The problem with your approach is the setting theref.currentwith a new value, doesn't cause a re-render, so theuseEffectmight not be called when you want it. In your case, something else causes a re-render (probably the state used for the conditional render), and so you avoid this problem.You can use
useStateinstead of auseRefbecause components also accept a function as aref. That would cause the component to re-render when the state updates with the ref:Another variation on the function as a ref idea, is to create a callback to observe the element, and pass it as the ref: