I've been seeing this pattern quite a bit:
// inside a component
const dimensions = useRef<DOMRect | null>(null)
useEffect(() => {
dimensions.current = someRef.current.getBoundingClientRect()
}, []);
The problem with nullable types like DOMRect | null
is that they tend to propagate throughout the codebase, and end
up forcing everywhere else to handle nullability. We end up with 10s of if (dimensions && ...)
or
dimensions?.width ?? 0
that could be avoided. Being able to get rid of the | null
part of the type right away
simplifies the rest of the codebase.
The pattern could instead be replaced with:
// static constant, outside the component
const EMPTY_DIMENSIONS = new DOMRect(0, 0, 0, 0)
// inside a component
const dimensions = useRef(EMPTY_DIMENSIONS)
// etc
In the rare cases where being able to tell if initialization has happened (which are much rarer than simple usages of the value), then we can easily:
const didInitialize = dimensions !== EMPTY_DIMENSIONS
Alternatively, we can also attach a flag directly on the type:
const EMPTY_DIMENSIONS = { isInitialized: false, width: 0, height: 0 }
// etc