0

I am trying to use useRef and useCallback together but my useRef is not updating sometime, it seems. It is actually weird and it happens only sometimes. Even if I use normal ref operating, it will behave the same.

function useRefCallback() {
  const ref = useRef(null);
  const setRef = useCallback(node => {
    ref.current = node;
  }, []);
  return [ref, setRef];
}

function MapWidget({ options }) {
  const [mapWidgetRef, setMapWidgetRef] = useRefCallback();
// I try to pass to another hook to get width and height of that mapWidgetRef.
  const [mapWidgetWidth, mapWidgetHeight] = useResizeObserver(mapWidgetRef); 

  return (
    <div ref={setMapWidgetRef}>
    ...
    </div>

}

If I try to print out mapWidgetRef I would get just object sometimes which is not good and it will make mapWidgetWidth, mapWidgetHeight undefined. Most of the time is okay and its working as expected.

Not Good

enter image description here

Good

enter image description here

How can I solve this?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Phyo
  • 27
  • 8

2 Answers2

0

It is important to give useCallback all the dependencies needed

const setRef = useCallback(node => {
    ref.current = node;
}, [ref]);

This however will make it ineffective, you could instead use ref as you normally would, and if some operation is needed that require memoization, use useCallback for that part of the code

iunfixit
  • 953
  • 3
  • 15
  • I tried using with normal useRef but it did not work and gave me same result. That's why I tried using together with callback. But still no luck. – Phyo Aug 31 '21 at 02:04
0

It's hard for me to understand

function useRefCallback() {
  const ref = useRef(null);
  const setRef = useCallback(node => {
    ref.current = node;
  }, []);
  return [ref, setRef];
}

A simple useRef should work for you already. Make sure to check ref.current before use.

  const ref = useRef()
  return <div ref={ref}>

You are kinda of working with old and new ref. To be honest the new ref covers both cases, only in some extreme case, the ref have to use the old ref syntax to get it working. But in general, the above lines should work.

NOTE: ref doesn't get updated in every render. It's only when the DOM gets changed, ex. mount, unmount, then it gets updated. So no need to use useCallback etc. It shouldn't work with those.

windmaomao
  • 7,120
  • 2
  • 32
  • 36
  • Yes Initially I tried using with normal useRef but it did not work and gave me same result. That's why I tried using together with callback. But still no luck. – Phyo Aug 31 '21 at 02:04