27 lines
691 B
TypeScript
27 lines
691 B
TypeScript
import {useEffect, useRef, useState} from "react"
|
|
|
|
export function useEffectOnce(effect:Function) {
|
|
const effectFn = useRef(effect)
|
|
const destroyFn = useRef<Function>()
|
|
const effectCalled = useRef(false)
|
|
const rendered = useRef(false)
|
|
const [, refresh] = useState(0)
|
|
|
|
if (effectCalled.current) {
|
|
rendered.current = true
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (!effectCalled.current) {
|
|
destroyFn.current = effectFn.current()
|
|
effectCalled.current = true
|
|
}
|
|
|
|
refresh(1)
|
|
|
|
return () => {
|
|
if (rendered.current === false) return
|
|
if (destroyFn.current) destroyFn.current()
|
|
}
|
|
}, [])
|
|
} |