Search code examples
reactjstypescriptuse-ref

Is it bad practice to use the null-forgiving operator with `useRef`?


Would the following be considered bad practice?

const Component: React.FC<{}> = () => {
    const ref = React.useRef<HTMLDivElement>(null!);

    return <div ref={ref} />;
}

Specifically, I'm referring to the use of null!.

Without the null-forgiving operator, we'd need to do a check like

if (ref.current) {
   // ... use ref.current
}

each time.


Solution

  • Would the following be considered bad practice?

    const Component: React.FC<{}> = () => {
        const ref = React.useRef<HTMLDivElement>(null!);
        
        return <div ref={ref} />;
    }
    

    Pretty much. It's not doing anything good for you, and it's potentially masking a null access later on – notably, while the component is being unmounted.

    Suppose we added an (unwisely coded) effect to the component, with a cleanup callback:

    useEffect(() => {
        ref.current.focus();
        return () => ref.current.blur();
    });
    

    When the effect cleanup is run, ref.current will be null. Typescript would normally detect this and report 'ref.current' is possibly null, but by initialising the ref with null! we've asserted (falsely) that ref.current is never null. So, instead of detecting the problem during coding, we get a runtime error.