How to make a React useRef() mutable

If you aren’t careful, Typescript assumes that your useRef() declarations are immutable (aka read-only). Which means you will get errors if you try to useRef() to store persistent variables, for example.

Here’s a breakdown from https://stackoverflow.com/questions/58017215/what-typescript-type-do-i-use-with-useref-hook-when-setting-current-manually

The function is set up with overflows if | null is added to the type.

function useRef<T>(initialValue: T): MutableRefObject<T>;
function useRef<T>(initialValue: T | null): RefObject<T>;

You get a read-only error if you type something like this: useRef<HTMLElement>(null)

You will NOT get a read-only error if you include | null in the generic typing.“

useRef<HTMLElement | null>(null); // 🎉