How to Fix "Object is possibly 'null'" TypeScript Error When Using useRef React Hook?

Find out how you can fix TypeScript errors when using the useRef React hook

When the useRef() hook is initialized with null, TypeScript may complain that "Object is possibly 'null'" when trying to access the current property on the reference object. For example:

const Foo = () => {
    const inputElem = useRef(null);

    useEffect(() => {
        // error: Object is possibly 'null'
        console.log(inputElem.current.value);
    }, []);

    return (
        <>
            <input type="text" ref={inputElem} defaultValue="foobar" />
        </>
    );
};

To fix this error, we simply need to make it null safe when accessing the current property value. For example:

const Foo = () => {
    const inputElem = useRef<HTMLInputElement>(null);

    useEffect(() => {
        // error: Property 'value' does not exist on type 'never'.
        console.log(inputElem?.current?.value);
    }, []);

    return (
        <>
            <input type="text" ref={inputElem} defaultValue="foobar" />
        </>
    );
};

If you're unable to use optional chaining (?.), then as an alternative you may instead simply add a check like so:

if (inputElem && inputElem.current) {
    console.log(inputElem.current.value);
}

As you can see in the example above, the first error we had is fixed after we added a type-safe access to the current property. However, now we have another error, "Property 'value' does not exist on type 'never'". This error happens because we haven't specified the correct type for ref.current. To understand this, let's have a look at the useRef type definition:

function useRef<T>(initialValue: T): MutableRefObject<T>

As you can see the return type of useRef is "MutableRefObject", which has the following type definition:

interface MutableRefObject<T> {
    current: T;
}

From the above type definitions, it's quite clear that passing a type to the useRef generic would set the correct type for the reference object's current property. For example:

const Foo = () => {
    const inputElem = useRef<HTMLInputElement>(null);

    useEffect(() => {
        console.log(inputElem?.current?.value);
    }, []);

    return (
        <>
            <input type="text" ref={inputElem} defaultValue="foobar" />
        </>
    );
};

And that should fix the TypeScript errors we had with the React useRef hook.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.