-
-
Save dariovr1/da1bc1c4b097195754a903a68d759de4 to your computer and use it in GitHub Desktop.
React Hooks BetterUseEffect - A replacement of useEffect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef } from "react"; | |
export const usePrevious = (value) => { | |
const ref = useRef(); | |
useEffect(() => { | |
ref.current = value; | |
}); | |
return ref.current; | |
} | |
export const useComponentDidUpdate = ( | |
effect, | |
dep = [] | |
) => { | |
const hasMounted = useRef(false); | |
useEffect(() => { | |
if (!hasMounted.current) { | |
hasMounted.current = true; | |
return; | |
} | |
effect(); | |
},dep); | |
} | |
export const useFirstRun = () => { | |
const firstrun = useRef(false); | |
useEffect(() => { | |
if (!firstrun.current) { | |
firstrun.current = true; | |
} | |
}) | |
return firstrun.current; | |
} | |
export const BetterUseEffect = ( | |
effect, | |
dep | |
) => { | |
const firstrun = useFirstRun(); | |
const prevDep = usePrevious(dep); | |
firstrun && effect({ | |
previus : prevDep, | |
changed : Object.keys(prevDep).filter(k => prevDep[k] !== dep[k]), | |
firstrun, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment