fleet/frontend/hooks/useDeepEffect.ts
Martavis Parker 384c987389
Removed all traces of Redux from the app! (#5287)
* clean up routes and useless components

* component clean up

* removed redux from routes

* rename file

* moved useDeepEffect hook with others

* removed redux, fleet, app_constants dirs; added types to utilities

* style cleanup

* typo fix

* removed unused ts-ignore comments

* removed redux packages!!!

* formatting

* fixed typing for simple search function

* updated frontend readme
2022-04-22 09:45:35 -07:00

32 lines
792 B
TypeScript

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
*/
export const useDeepEffect = (fn: () => void, deps: Array<any>) => {
const isFirst = useRef(true);
const prevDeps = useRef(deps);
useEffect(() => {
const isSame = prevDeps.current.every((obj, index) =>
isEqual(obj, deps[index])
);
if (isFirst.current || !isSame) {
fn();
}
isFirst.current = false;
prevDeps.current = deps;
}, [deps, fn]);
};
export default useDeepEffect;