react icon indicating copy to clipboard operation
react copied to clipboard

[Basic] useRef in useEffect Object is possibly undefined

Open thisconnect opened this issue 6 years ago • 17 comments

What cheatsheet is this about? (if applicable)

How to use typescript and useRef

What's your issue or idea?

import React, { useEffect, useRef } from 'react'
export default function() {
  const myRef = useRef()
  useEffect(() => {
    myRef.current.classList.add('something')
    // Object is possibly 'undefined'.ts(2532)
  })
  return (
    <div ref={myRef}></div>
  )
}

The following "works" / "typescript doesn't complain"... but is that the proper way?

import React, { useEffect, useRef } from 'react'

export default function() {
  const myRef = useRef(null)
  useEffect(() => {
    const node = myRef.current as any
    node.classList.add('something')
  })
  return (
    <div ref={myRef}></div>
  )
}

thisconnect avatar Feb 16 '20 10:02 thisconnect

Typescript seems to like this one

import React, { useEffect, useRef } from 'react'

export default function() {
  const myRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    const node = myRef.current
    node?.classList.add('something')
    // ^ note the new ? similar to `if (node)`
  })
  return (
    <div ref={myRef}></div>
  )
}

thisconnect avatar Feb 16 '20 10:02 thisconnect

That second one is the proper usage.

On Sun, Feb 16, 2020 at 5:47 AM tcme [email protected] wrote:

Typescript seems to like this one

import React, { useEffect, useRef } from 'react' export default function() { const myRef = useRef(null) useEffect(() => { const node = myRef.current node?.classList.add('something') // ^ note the new ? similar to if (node)

}) return (

) }

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/187?email_source=notifications&email_token=AC5MIAMEBGQZ2UGE7S2RO23RDEKVBA5CNFSM4KWBX52KYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEL4DJEI#issuecomment-586691729, or unsubscribe https://github.com/notifications/unsubscribe-auth/AC5MIALMZ2NQLG44FXRH62TRDEKVBANCNFSM4KWBX52A .

ferdaber avatar Feb 16 '20 14:02 ferdaber

That second one is the proper usage.

ok thanks I'll go with that, but technically useRef does not directly return a HTMLDivElement, is that correct?

It returns some object that has a current property that is the HTMLDivElement… Am I missing something?

thisconnect avatar Feb 16 '20 16:02 thisconnect

hmm 🤔 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/8a31a2fe9e8417d47550db09e5f9f50fd09a8e60/types/react/index.d.ts#L838

thisconnect avatar Feb 16 '20 16:02 thisconnect

useRef is a generic so you can pass any type you want into it so that it can internally know what .current is supposed to be. Since you're using null as the initial value, I think you need to add that to your type you're declaring as well. So useRef<HTMLDivElement>(null) should be useRef<HTMLDivElement | null>(null) so typescript knows your myRef.current property can be HTMLDivElement or null.

You don't always have to declare the type your ref will be if you know the type won't change. For example, if you do something like

const myRef = useRef(false);
if (!myRef.current) {
    myRef.current = true
}

typescript will infer it as a boolean:

image

hellatan avatar Feb 17 '20 04:02 hellatan

@hellatan there are overloads for useRef such that if you use a type param T vs T | null the resultant object is different:

// @type = { readonly current: HTMLDivElement | null }
const refObjectToPassIntoRefProp = useRef<HTMLDivElement>(null)
// @type = { current: HTMLDivElement | null }
const refObjectYouMaintain = useRef<HTMLDivElement | null>(null)
// @type = { current: HTMLDivElement | undefined }
const refObjectYouMaintainToo = useRef<HTMLDivElement>()

With the first, the current property of the object is read-only to you, the consumer. It's meant to be passed into React as the pointer is maintained by React. In practice, you can still mutate the current property of something you pass into React but it's not recommended as React is supposed to be the owner.

ferdaber avatar Feb 18 '20 14:02 ferdaber

@ferdaber so do you mean when you don't pass in T | null, typescript will complain if you try to do myRef.current = 'some new ref'?

hellatan avatar Feb 18 '20 15:02 hellatan

Correct.

ferdaber avatar Feb 18 '20 15:02 ferdaber

Good to know, it makes sense now. I was looking for readonly (but didn't know it exists) so your first example useRef<HTMLDivElement>(null) is exactly what I want.

thisconnect avatar Feb 21 '20 09:02 thisconnect

The 3rd example errors for me

// @type = { current: HTMLDivElement | undefined }
const refObjectYouMaintainToo = useRef<HTMLDivElement>()

Error

Type 'MutableRefObject<HTMLDivElement | undefined>' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
  Type 'MutableRefObject<HTMLDivElement | undefined>' is not assignable to type 'RefObject<HTMLDivElement>'.
    Types of property 'current' are incompatible.
      Type 'HTMLDivElement | undefined' is not assignable to type 'HTMLDivElement | null'.
        Type 'undefined' is not assignable to type 'HTMLDivElement | null'.  TS2322

code snippet (top component no conditional render)

  const myRef = useRef<HTMLDivElement>()
  return (
    <div className="App">
      <div ref={myRef}></div>

Maybe because I use CRA, which is a little behind @types/react current 6.9.19, latest 16.9.21

thisconnect avatar Feb 21 '20 09:02 thisconnect

updating typescript to 3.8.2 and @types/react to 16.9.21 didn't help

thisconnect avatar Feb 21 '20 09:02 thisconnect

If you're using a ref object to pass into a ref prop for an element, you need to use the | null overload, otherwise it will complain to you. The third form is for cases where you maintain the pointer yourself (instead of React).

ferdaber avatar Feb 21 '20 15:02 ferdaber

thanks for your explanation

thisconnect avatar Feb 22 '20 08:02 thisconnect

@thisconnect you are welcome to PR if you feel the cheatsheet could be improved to help you on this :)

swyxio avatar Mar 25 '20 22:03 swyxio

why not use like this "useRef<any>()" it works fine btw

ShubhamChaudharyy avatar Aug 23 '20 04:08 ShubhamChaudharyy

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions!

stale[bot] avatar Oct 22 '20 15:10 stale[bot]

think we have addressed this well here https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/hooks/#useref

swyxio avatar Oct 22 '20 18:10 swyxio