When using useRef() in TypeScript and setting its .current value manually, the type depends on what you want to store in the ref. Here are some common cases:
1. For DOM elements
If you are using useRef() for referencing a DOM element (like div, input, etc.), you should use the appropriate HTML element type:
import { useRef, useEffect } from "react";
function Example() {
const divRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
if (divRef.current) {
divRef.current.style.backgroundColor = "lightblue";
}
}, []);
return <div ref={divRef}>Hello, TypeScript!</div>;
}
2. For mutable values (manually setting current)
If you're storing a mutable value that isn’t tied to the DOM (e.g., a number, object, or function), use useRef<T>() with the initial type:
const countRef = useRef<number>(0);
countRef.current = 5; // Valid
3. For objects or custom data
If you want to store a custom object or value:
interface MyData {
name: string;
age: number;
}
const dataRef = useRef<MyData | null>(null);
dataRef.current = { name: "John", age: 25 };