react icon indicating copy to clipboard operation
react copied to clipboard

Bug: react-hooks/refs false positive using IntersectionObserver

Open ashleymercer opened this issue 8 months ago • 2 comments

React version: 17.0.2 eslint-plugin-react: 7.37.5 eslint-plugin-react-hooks: 7.0.1

Steps To Reproduce

Attempting to create a simple hook to wrap IntersectionObserver:

function useIntersectionObserver(options: Partial<IntersectionObserverInit>) {

  const callbacks = useRef(new Map<string, IntersectionCallback>());

  const onIntersect = useCallback((entries: ReadonlyArray<IntersectionObserverEntry>) => {
    entries.forEach(entry => callbacks.current.get(entry.target.id)?.(entry.isIntersecting)) },
    []
  );

  const observer = useMemo(() => 
    // This line incorrectly reports "Error: Cannot access refs during render"
    new IntersectionObserver(onIntersect, options),
    [onIntersect, options]
  );

  // Some other stuff here
}

Link to code example:

The current behavior

The above code reports the following when running eslint:

error  Error: Cannot access refs during render

React refs are values that are not needed for rendering. Refs should only be accessed outside of render, 
such as in event handlers or effects. Accessing a ref value (the `current` property) during render can 
cause your component not to update as expected (https://react.dev/reference/react/useRef).

common\ReactHooks.ts:97:30
|
|   const observer = useMemo(() =>
|     new IntersectionObserver(onIntersect, options), [onIntersect, options]);
|                              ^^^^^^^^^^^ Cannot access ref value during render
|

The expected behavior

The code is not using a ref (at least, not directly) and anyway it isn't rendering - so it's a mystery as to why the error is reported, unless I'm missing some subtle behaviour?

ashleymercer avatar Mar 09 '26 14:03 ashleymercer

A2ABench has an accepted answer for this imported thread.

  • Thread: https://a2abench-api.web.app/q/cmmo0j2qn005jpv0bp7v7ehv7
  • Accepted at: 2026-03-25T19:35:11.176Z
  • Accepted answer agent: ai village
  • Answer preview: "No matching threads were found for this query."

khalidsaidi avatar Mar 25 '26 19:03 khalidsaidi

This seems to be a systematic issue, rather than being specifically about IntersectionObserver. I'm running into the same error with React Native's PanResponder:

  const swipeAxisRef = useRef<SwipeGestureAxis>(undefined);

 // ...

  const panResponder = PanResponder.create({
    onMoveShouldSetPanResponder: (_, gesture) => {
      const axis = getGestureAxis(gesture.dx, gesture.dy);
      if (axis == null) {
        return false;
      }

      swipeAxisRef.current = axis;
      return true;
    },

How exactly does React Compiler determine which functions are run "during render"? There is nothing in this code that suggests that.

CC @josephsavona

SimpleCreations avatar Jun 16 '26 16:06 SimpleCreations