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?
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Can you explain more about when to use refs instead of state in React?
What are some common mistakes when typing refs in TypeScript?
Can you show how to type a ref for a custom component?
Awesome!
Completion rate improved to 4.17
Typing Refs with useRef
Scorri per mostrare il menu
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?
Grazie per i tuoi commenti!