Why Does This Happen?
When the React 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, the following demonstrates this:
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" />
);
};
This error occurs because TypeScript cannot guarantee that the reference object is not null
when you're accessing its properties.
How to Fix the Issue?
This error can be fixed by:
- Specifying the correct type for the reference object using the
useRef<T>()
generic, and; - Making sure that you access the reference object's properties in a null-safe way (e.g. using optional chaining).
For example, you can implement these steps in the following way:
const Foo = () => {
// 1: specify correct type for reference object using generics
const inputElem = useRef<HTMLInputElement>(null);
useEffect(() => {
// 2: access the reference object's properties in a null-safe way
console.log(inputElem?.current?.value);
}, []);
return (
<input type="text" ref={inputElem} defaultValue="foobar" />
);
};
In this example, the reference object points to an HTML <input>
element; therefore, the type HTMLInputElement
is specified. You should change it to match the element you wish to keep a reference to.
Please note that without specifying the type for the reference object using generics, you will get the "Property '...' does not exist on type 'never'.
" error.
If you're unable to use optional chaining (?.
), then as an alternative, you may perform the following check instead:
if (inputElem && inputElem.current) {
console.log(inputElem.current.value);
}
These approaches ensure type safety and resolve the TypeScript errors associated with the React useRef()
hook mentioned earlier.
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.