Home > Back-end >  Should I use useRef over createRef with forwardRef?
Should I use useRef over createRef with forwardRef?

Time:12-06

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.

CodePudding user response:

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

  • Related