2021-07-10 17:29:27 +00:00
|
|
|
import { useEffect, useRef } from "react";
|
|
|
|
|
import { isEqual } from "lodash";
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
*
|
|
|
|
|
* @param fn Anonymous function passing into the hook
|
|
|
|
|
* @param deps What dependencies to watch for changes
|
|
|
|
|
*
|
|
|
|
|
* Adapted from https://betterprogramming.pub/how-to-use-the-react-hook-usedeepeffect-815818c0ad9d,
|
|
|
|
|
* this hook does a deeper check for changes within objects and arrays
|
|
|
|
|
*/
|
|
|
|
|
|
2026-05-05 12:58:21 +00:00
|
|
|
export const useDeepEffect = (fn: () => void, deps: ReadonlyArray<unknown>) => {
|
2021-07-10 17:29:27 +00:00
|
|
|
const isFirst = useRef(true);
|
|
|
|
|
const prevDeps = useRef(deps);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2026-05-05 12:58:21 +00:00
|
|
|
const isSame =
|
|
|
|
|
prevDeps.current.length === deps.length &&
|
|
|
|
|
prevDeps.current.every((obj, index) => isEqual(obj, deps[index]));
|
2021-07-10 17:29:27 +00:00
|
|
|
|
|
|
|
|
if (isFirst.current || !isSame) {
|
|
|
|
|
fn();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
isFirst.current = false;
|
|
|
|
|
prevDeps.current = deps;
|
|
|
|
|
}, [deps, fn]);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default useDeepEffect;
|