Skip to main content
sysadmin.my

Back to all posts

useUnstrictEffect

Published on by dab · 1 min read

Table of Contents

Show more

when you want to use <StrictMode> but do not want your useEffects to be repeated

import React, { useEffect, useRef } from 'react'
const useUnstrictEffect = function (og_func, deps) {
const ref_obj = {}
const ref_teardown = useRef()
useEffect(() => {
const id_timeout = setTimeout(() => {
// do the original thing //
const func_teardown = og_func()
ref_teardown.current = () => {
func_teardown()
return
}
return
}, 1)
return () => {
if (ref_teardown.current) {
ref_teardown.current()
ref_teardown.current = undefined
}
else {
// immediate Unmount = STOP og_func from ever running
clearTimeout(id_timeout)
}
return
}
}, (deps === undefined ? [] : deps))
return ref_obj
}