useIntersection warning with React 19
What is the current behavior?
Migrating to Nextjs 15.1 and React 19, the useIntersection started to throw a ts warning.
The code in the docs does not work anymore.
const intersectionRef = React.useRef(null);
const intersection = useIntersection(intersectionRef, { ... }); <<< intersectionRef
The error is:
Argument of type 'RefObject<null>' is not assignable to parameter of type 'RefObject<HTMLElement>'.
Type 'null' is not assignable to type 'HTMLElement'.ts(2345)
useIntersection signature should accept RefObject<HTMLElement | null>.
What is the expected behavior? To not throw a warning. It actually keeps working.
A little about versions:
- OS: macOS 15.1.1
- Browser (vendor and version): Chrome 131
- React: 19
react-use: 17.5.1- Did this worked in the previous package version? No
The same issue with useFullscreen
The same issue with useHoverDirty
also useScroll
The overarching issue is that the useRef now requires 1 param, which is usually null or undefined. For those there is convenience overload, so each time we get back RefObject<T | null> or RefObject<T | undefined>. That will never match the RefObject<HTMLElement> which is defined in all the hooks e.g. https://github.com/streamich/react-use/blob/ad33f76dfff7ddb041a9ef74b80656a94affaa80/src/useScroll.ts#L11
See Ref changes here:
https://github.com/DefinitelyTyped/DefinitelyTyped/pull/69022
I recently ran into this and I haven't found a way to fix it using react-use other than downgrading to React 18.
This library does more or less the same thing and I was able to "move" without much difficulty, keeping React 19. Maybe it can be useful to someone.