reactjsreact-hooksmemoization

Unexpected memoization in functions


My case is very straightforward - everyone has this kind of hooks.

It contains state and returns some method for operating this state.

My question is why I sometimes get state variable (loadedPolys) memoized inside the function (updateAndGetPolygon) and having these two console logs showing different value?

It is not affected by wrapping updateAndGetPolygon with useCallback. Only starts working with working around useState.

Thanks!

export function useLoadedViewports() {
  const [loadedPolys, setLoadedPolys] = useState([]);
  console.log('loadedPolys outside:', loadedPolys);

  const updateAndGetPolygon = (poly) => {
    console.log('loadedPolys inside:', loadedPolys);

    // Some logic setting updated state
    const differenceResult = difference(poly, loadedPolys);
    const unionResult = union(poly, loadedPolys);
    setLoadedPolys(unionResult);
    return differenceResult;
  };

  return {
    updateAndGetPolygon,
  };
}

Solution

  • So, I found the answer by myself. This was caused by using this 'updateAndGetPolygon' function inside function memoized with useCallback. I have a quite complex component with following call stack:

    useCallback(functionA) =calls=> someOtherFunction =calls=> updateAndGetPolygon function where I had unexpected memoization.

    So if you use nested functions in useCallback, everything related to states used in all of these functions seem to memoize inside them.

    Btw, if anyone has any links on articles on how this is done in React, please share.