What's the difference between useRef(null) and useRef(undefined) (or just useRef())?
In TypeScript, the results end up with different types:
const undefinedRef: React.MutableRefObject<undefined> = useRef(undefined)
conse noArgRef: React.MutableRefObject<undefined> = useRef()
const nullRef: React.MutableRefObject<null> = useRef(null)
This also has further consequences, when passing the ref to another element:
const nullRef = useRef(null)
<div ref={nullRef} /> // this works
const undefinedRef = useRef()
<div ref={undefinedRef} /> // compiler failure!
/*
Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<HTMLDivElement>'.
Types of property 'current' are incompatible.
Type 'undefined' is not assignable to type 'HTMLDivElement | null'.ts(2322)
*/
Despite the compiler failure, it still works for my use case (using the useClickAway hook from react-use)
What's the impact at this, looking beyond the TypeScript types?
Here's a CodeSandbox that recreates the failure: https://codesandbox.io/s/prod-resonance-j9yuu?file=/src/App.tsx