The useRef()
hook in React is commonly used for accessing DOM elements or storing mutable values without causing re-renders.
In TypeScript, when using useRef
, you should specify the type of the element you are referring to. This is done by using React.RefObject<ElementType>
where ElementType
is the type of the DOM element, like HTMLInputElement
for an input element. If the ref stores a mutable value, its type should be defined as well.
For instance, consider a ref attached to an input element:
const inputRef = useRef<HTMLInputElement>(null);
Here, useRef<HTMLInputElement>(null)
initializes inputRef with null, but TypeScript knows it will refer to an HTMLInputElement
. This provides autocomplete and type checking when you interact with inputRef.current
.
If you're using the ref to store a mutable value (not a DOM element), you can define its type like this:
const valueRef = useRef<number>(0);
This initializes valueRef with a default value of 0
, and TypeScript will ensure that valueRef.current
is always treated as a number.
<input>
element, then focus the input when the component mounts.Ask me for help or clarification: