0

Following up to What's the difference between `useRef` and `createRef`?. I have a functional component that uses React.forwardRef.

My question is specifically because of TypeScript failing.

Using

const textRef = createRef<typeof RNText>()
...
<HocText ref={textRef}>HocTextOne</HocText>

works correctly but

const textRef = useRef<typeof RNText>()
...
<HocText ref={textRef}>HocTextOne</HocText>

yields

Type 'MutableRefObject<typeof Text | undefined>' is not assignable to type 'Ref | undefined'

Some articles show that we should be using useRef for functional components, but TypeScript is generating an error.

Forcing a cast like

const textRef = useRef<typeof RNText>() as RefObject<typeof RNText>

makes it compile but I am not sure if it is the right thing to do.

Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265
  • 1
    It's a side effect of how the type for useRef is defined, you can use `const textRef = useRef< typeof RNText >(null)` to fix this. This will change the type of the ref to RefObject – nullptr Dec 06 '22 at 06:42
  • Your user name is pretty ironic considering the solution. You can post that as the answer. – Archimedes Trajano Dec 06 '22 at 07:09

1 Answers1

1

It's a side effect of how the type for useRef is defined, you can use const textRef = useRef<typeof RNText>(null) to fix this. This will change the type of the ref to RefObject

nullptr
  • 3,701
  • 2
  • 16
  • 40