Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Typing Refs with useRef | Typing React Components
TypeScript Essentials for React

bookTyping 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 as HTMLDivElement, HTMLInputElement, or your custom type;
  • When initializing a ref with null, include null in the type if the value might be absent;
  • Use optional chaining (?.) when accessing properties on ref.current to 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?

question mark

What type should you use for a ref pointing to an HTML input element?

Select the correct answer

question mark

Why is it important to type refs in React?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 4

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Awesome!

Completion rate improved to 4.17

bookTyping Refs with useRef

Desliza para mostrar el menú

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 as HTMLDivElement, HTMLInputElement, or your custom type;
  • When initializing a ref with null, include null in the type if the value might be absent;
  • Use optional chaining (?.) when accessing properties on ref.current to 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?

question mark

What type should you use for a ref pointing to an HTML input element?

Select the correct answer

question mark

Why is it important to type refs in React?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 4
some-alt