Skip to content

Instantly share code, notes, and snippets.

@dariovr1
Created September 8, 2020 15:51
Show Gist options
  • Save dariovr1/da1bc1c4b097195754a903a68d759de4 to your computer and use it in GitHub Desktop.
Save dariovr1/da1bc1c4b097195754a903a68d759de4 to your computer and use it in GitHub Desktop.
React Hooks BetterUseEffect - A replacement of useEffect
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