Typing Refs with useRef
When working with React, you often need to interact with the DOM directly or store mutable values that persist across renders. The useRef hook is the standard way to create these references, but to take full advantage of TypeScript, you must properly type your refs. Typing refs ensures safety when accessing properties like current, especially when dealing with HTML elements or custom values.
To type a ref for an HTML element, such as an input, you use the corresponding DOM type. For instance, if you want a ref to an HTML input element, you declare it as useRef<HTMLInputElement>(null). This tells TypeScript that ref.current will either be null or an HTMLInputElement, so you get accurate autocompletion and type checking when you access properties like value or focus().
For non-DOM values, such as storing a mutable counter or any custom object, you define the type directly. If you want a ref to hold a number, you use useRef<number>(0). This allows you to store and update values that persist across renders without causing re-renders, and TypeScript will enforce the correct type for ref.current.
Here are some common patterns you will encounter and how to type them correctly to avoid errors:
Typing a ref for an HTML input element:
import { useRef } from "react";
function TextInput() {
const inputRef = useRef<HTMLInputElement>(null);
const focusInput = () => {
inputRef.current?.focus();
};
return (
<div>
<input ref={inputRef} />
<button onClick={focusInput}>Focus input</button>
</div>
);
}
Typing a ref for a non-DOM value:
import { useRef } from "react";
function Timer() {
const intervalId = useRef<number | null>(null);
const startTimer = () => {
intervalId.current = window.setInterval(() => {
console.log("Tick");
}, 1000);
};
const stopTimer = () => {
if (intervalId.current !== null) {
clearInterval(intervalId.current);
}
};
return (
<div>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
</div>
);
}
Avoiding type errors with refs:
- Always provide the correct type argument to
useRef, such asHTMLDivElement,HTMLInputElement, or your custom type; - When initializing a ref with
null, includenullin the type if the value might be absent; - Use optional chaining (
?.) when accessing properties onref.currentto avoid runtime errors when the ref is not yet attached.
1. What type should you use for a ref pointing to an HTML input element?
2. Why is it important to type refs in React?
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Awesome!
Completion rate improved to 4.17
Typing Refs with useRef
Svep för att visa menyn
When working with React, you often need to interact with the DOM directly or store mutable values that persist across renders. The useRef hook is the standard way to create these references, but to take full advantage of TypeScript, you must properly type your refs. Typing refs ensures safety when accessing properties like current, especially when dealing with HTML elements or custom values.
To type a ref for an HTML element, such as an input, you use the corresponding DOM type. For instance, if you want a ref to an HTML input element, you declare it as useRef<HTMLInputElement>(null). This tells TypeScript that ref.current will either be null or an HTMLInputElement, so you get accurate autocompletion and type checking when you access properties like value or focus().
For non-DOM values, such as storing a mutable counter or any custom object, you define the type directly. If you want a ref to hold a number, you use useRef<number>(0). This allows you to store and update values that persist across renders without causing re-renders, and TypeScript will enforce the correct type for ref.current.
Here are some common patterns you will encounter and how to type them correctly to avoid errors:
Typing a ref for an HTML input element:
import { useRef } from "react";
function TextInput() {
const inputRef = useRef<HTMLInputElement>(null);
const focusInput = () => {
inputRef.current?.focus();
};
return (
<div>
<input ref={inputRef} />
<button onClick={focusInput}>Focus input</button>
</div>
);
}
Typing a ref for a non-DOM value:
import { useRef } from "react";
function Timer() {
const intervalId = useRef<number | null>(null);
const startTimer = () => {
intervalId.current = window.setInterval(() => {
console.log("Tick");
}, 1000);
};
const stopTimer = () => {
if (intervalId.current !== null) {
clearInterval(intervalId.current);
}
};
return (
<div>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
</div>
);
}
Avoiding type errors with refs:
- Always provide the correct type argument to
useRef, such asHTMLDivElement,HTMLInputElement, or your custom type; - When initializing a ref with
null, includenullin the type if the value might be absent; - Use optional chaining (
?.) when accessing properties onref.currentto avoid runtime errors when the ref is not yet attached.
1. What type should you use for a ref pointing to an HTML input element?
2. Why is it important to type refs in React?
Tack för dina kommentarer!