Skip to content

Bug: react-hooks/refs false positive using IntersectionObserver #35982

@ashleymercer

Description

@ashleymercer

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions