reactjscallbackcomponentsresize-observer

Get react context data in ResizeObserver callback


I have the following React getView component

function getView() {
  const mainContext = useContext(MainContext);

  useEffect(() => {
    // data has values here
    const activeDiv = document.getElementById('active-div');
    new ResizeObserver(dataMethod).observe(activeDiv);

  }, [mainContext?.data])

  function dataMethod() {
    let data = mainContext?.data;  // data is always empty here
  }

  ...
}

For some reason mainContext?.data is always empty. How can I access the mainContext?.data in the dataMethod() function?


Solution

  • I was not able to reproduce the behaviod "data is always empty here" but the possible error you are getting is due to you are not calling unobserve/disconnect of the ResizeObserver instance in the cleanup function of your useEffect. So you end up with (more than 1) Observer and your function is called from each of them on resize, utilizing closure-captured values that were captured at the moment when observe was called.

    What can you try - add a useRef variable to eliminate possible closure issues and to prevent the need to create/remove ResizeObserver on mainContext.data changes.

    const mainContext = useContext(MainContext);
    const dataRef = useRef(mainContext?.data);
    
    useEffect(() => {
      dataRef.current = mainContext?.data;
    }, [mainContext?.data]);
    
    useEffect(() => {
      const dataMethod = () => {
        let data = dataRef.current;
        console.log("dataMethod data: ", data);
      };
    
      const activeDiv = document.getElementById("active-div");
      const obs = new ResizeObserver(dataMethod);
      obs.observe(activeDiv);
    
      return () => {
        obs.disconnect();
      };
    }, []);
    

    Edit determined-water-9tribt