/
🎣

useRef

react
Table of contents
  • TypeScript
  • Example
  • Docs: reactjs.org/docs/ho...nce.html
  • TS/React docs: github.com/typescri...EADME.md

TypeScript

When using useRef, you have two options when creating a ref container that does not have an initial value:

ts
const ref1 = useRef<HTMLElement>(null!)
const ref2 = useRef<HTMLElement | null>(null)

The first option will make ref1.current read-only, and is intended to be passed in to built-in ref attributes that React will manage (because React handles setting the current value for you).

The second option will make ref2.current mutable, and is intended for "instance variables" that you manage yourself.

Example

tsx
import React, { useRef } from 'react'
export const TextInputWithFocusButton = () => {
// initialise with null, but tell TypeScript we are looking for an HTMLInputElement
const inputEl = React.useRef<HTMLInputElement | null>(null)
const onButtonClick = () => {
// strict null checks need us to check if inputEl and current exist.
// but once current exists, it is of type HTMLInputElement, thus it
// has the method focus! ✅
if (inputEl && inputEl.current) {
inputEl.current.focus()
}
}
return (
<>
{/* in addition, inputEl only can be used with input elements. Yay! */}
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
)
}
Want to make your own site like this?
Try gatsby-theme-code-notes by Zander Martineau.
Notes on code. My second brain, by Zander Martineau.