Line data Source code
1 : import type {MutableRefObject, RefObject} from 'react'
2 : import {useCallback, useRef, useState} from 'react'
3 :
4 : /// There are certain situations where a ref might be set after the current render cycle for a
5 : /// component has finished. e.g. a forward ref from a conditionally rendered child component.
6 : /// In these situations, we need to force a re-render, which is done here by the useState hook.
7 1 : export function useRenderForcingRef<TRef>(value?: TRef) {
8 1 : const [refCurrent, setRefCurrent] = useState<TRef | null>(value || null)
9 1 : const ref = useRef<TRef>(null) as MutableRefObject<TRef | null>
10 1 : ref.current = refCurrent
11 :
12 1 : const setRef = useCallback(
13 1 : (newRef: TRef | null) => {
14 1 : ref.current = newRef
15 1 : setRefCurrent(newRef)
16 1 : },
17 1 : [ref],
18 : )
19 1 : return [ref as RefObject<TRef>, setRef] as const
20 1 : }
|