Should I use useRef over createRef with forwardRef?

Should I use useRef over createRef with forwardRef?

Problem Description:

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.


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

works correctly but

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


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.

Solution – 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

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.