Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useRef value is undefined on initial render

I'm making a map with react and react-leaflet. React Leaflet has a class called FeatureGroup, which I want to access on the first render using the useRef hook from React and then accessing the value in a useEffect function. However on initial render the ref is undefined (markerRef.current returns null). Only after I make any sort of changes to the code, save and the React app reloads it gets the value

Can you tell me what I'm doing wrong and how I can make it so that markerRef.current is not null on the initial render?

Please find the abbreviated code for the component below:

import {useRef} from 'react';
import {FeatureGroup, //... } from 'react-leaflet';

const MapView = ({breweries}) => {
  const markerGroupRef = useRef(null);
  //...
  useEffect(() => {
    if(markerGroupRef.current) {
      //here I want to access a method called getBounds() which is in the markerGroupRef.current object 
      //but markerGroupRef.current has null value and so it doesn't execute
      //when making a save change and react app reloads it has the FeatureGroup class as value as expected
      console.log(markerGroupRef.current)
    }
  }, [markerGroupRef])
  //...
  return (
            <FeatureGroup ref={markerGroupRef}>
              {breweries && breweries.map(brewery => <Brewery key={breweries.indexOf(brewery)} brewery={brewery}/>)}
              {breweryStore && breweryStore.searchLocation &&  <LocationMarker markerPosition={{lat: breweryStore.searchLocation.lat, lng: breweryStore.searchLocation.lon}}/>}
            </FeatureGroup>
    );
  }
like image 541
mivd Avatar asked Feb 20 '26 09:02

mivd


1 Answers

References create by useRef do not trigger component rerenders. So the useRef hook you created will never execute. Also since you initialized the ref to null, at the start of the first render, it will remain null. During the first render, the ref={markerGroupRef} on FeatureGroup will update it, but again it won't trigger another render. State must be modified to trigger any possible rerenders.

You might want to use a callback ref as indicated here

function MeasureExample() {
  const [height, setHeight] = useState(0);

  const measuredRef = useCallback(node => {
    if (node !== null) {
      setHeight(node.getBoundingClientRect().height);
    }
  }, []);

  return (
    <>
      <h1 ref={measuredRef}>Hello, world</h1>
      <h2>The above header is {Math.round(height)}px tall</h2>
    </>
  );
}

and justified here here

Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

like image 141
rubixibuc Avatar answered Feb 22 '26 23:02

rubixibuc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!