Files
qapi/src/components/useRefEffect.ts
T
34099eaafb bring EditCodec component
Co-authored-by: Josep M Sobrepere <jm.sobrepere@gmail.com>
Co-authored-by: Carlo Sala <carlosalag@protonmail.com>
Co-authored-by: Hannah Redler <hannahjredler@gmail.com>
2024-10-22 17:49:18 +02:00

31 lines
780 B
TypeScript

import { useCallback, useEffect, useRef } from "react"
export const useRefEffect = <T extends any>(
effect: (value: T) => () => void,
deps: any[] = [],
) => {
const ref = useRef<[(() => void) | null, T] | null>(null)
const setRef = useCallback((value: T | null) => {
if (ref.current?.[0]) {
ref.current?.[0]()
}
ref.current = value ? [effect(value), value] : null
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
if (ref.current && !ref.current[0]) {
ref.current[0] = effect(ref.current[1])
}
return () => {
if (ref.current) {
ref.current[0]?.()
ref.current[0] = null
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps)
return setRef
}