Просмотр исходного кода

Added hook utils to debug use effects

jnfrati 4 лет назад
Родитель
Сommit
da4fe8f18a

+ 34 - 0
dashboard/src/shared/hooks/useEffectDebugger.ts

@@ -0,0 +1,34 @@
+import { useEffect } from "react";
+import { usePrevious } from "./usePrevious";
+
+export const useEffectDebugger = (
+  effectHook: any,
+  dependencies: any,
+  dependencyNames: any = []
+) => {
+  const previousDeps = usePrevious(dependencies, []);
+
+  const changedDeps = dependencies.reduce(
+    (accum: any, dependency: any, index: any) => {
+      if (dependency !== previousDeps[index]) {
+        const keyName = dependencyNames[index] || index;
+        return {
+          ...accum,
+          [keyName]: {
+            before: previousDeps[index],
+            after: dependency,
+          },
+        };
+      }
+
+      return accum;
+    },
+    {}
+  );
+
+  if (Object.keys(changedDeps).length) {
+    console.log("[use-effect-debugger] ", changedDeps);
+  }
+
+  useEffect(effectHook, dependencies);
+};

+ 9 - 0
dashboard/src/shared/hooks/usePrevious.ts

@@ -0,0 +1,9 @@
+import { useEffect, useRef } from "react";
+
+export const usePrevious = (value: any, initialValue: any) => {
+  const ref = useRef(initialValue);
+  useEffect(() => {
+    ref.current = value;
+  });
+  return ref.current;
+};