乐闻世界logo
搜索文章和话题

How to use React useRef hook with typescript?

1个答案

1

When using useRef in TypeScript, you must specify the correct type parameter to inform TypeScript about the type of value the reference (ref) will point to. useRef is typically used in two main scenarios:

  1. Referencing DOM elements.
  2. Storing a mutable value that can change throughout the component's lifecycle, but changing it does not trigger a re-render.

I will provide examples of using useRef in TypeScript for each of these scenarios.

Referencing DOM Elements

When you want to directly manipulate DOM elements, you can use useRef. In TypeScript, you should specify the correct DOM element type as the type parameter for useRef.

For example, if you want to reference a <div> element:

tsx
import React, { useRef, useEffect } from 'react'; const MyComponent: React.FC = () => { // Create a reference with HTMLDivElement as the type parameter const divRef = useRef<HTMLDivElement>(null); useEffect(() => { if (divRef.current) { // Now you can safely access the div DOM element console.log(divRef.current.innerHTML); } }, []); return <div ref={divRef}>Hello, world!</div>; };

In this example, we inform TypeScript that divRef is a reference pointing to HTMLDivElement.

Storing Mutable Values

Another common use case for useRef is when you need to store a mutable value that you do not want changing to trigger a re-render. Unlike useState, modifying the current property of the object returned by useRef does not trigger a component re-render.

Suppose we want to track how many times the component has been rendered:

tsx
import React, { useRef, useEffect } from 'react'; const MyComponent: React.FC = () => { // Create a reference with number as the type parameter, initialized to 0 const renderCountRef = useRef<number>(0); useEffect(() => { // Update the current render count every time the component renders renderCountRef.current = renderCountRef.current + 1; console.log(`Component has been rendered ${renderCountRef.current} times`); }); return <div>Check the console to see the render count.</div>; };

In this example, we use number as the type parameter for useRef because we know the reference will point to a numeric value.

In summary, when using useRef in TypeScript, providing the correct type parameter is essential. This helps the type checker validate your code and provides accurate auto-completion and error hints.

2024年6月29日 12:07 回复

你的答案