Create Custom useEffect in ReactJs - salimakhtar92/ReactJs GitHub Wiki

Create a custom hook file custom-use-effect.js

import { useRef } from "react";

const useEffectCustomHook = (callBack, dependency) => {
  const isFirstRender = useRef(true);
  const pervDependency = useRef([]);

  if (isFirstRender.current) {
    isFirstRender.current = false;
    const cleanup = callBack();
    return () => {
      if (cleanup && typeof cleanup === "function") {
        cleanup();
      }
    };
  }

  const isDependencyChanged = dependency
    ? JSON.stringify(pervDependency.current) !== JSON.stringify(dependency)
    : true;

  if (isDependencyChanged) {
    const cleanup = callBack();
    if (cleanup && typeof cleanup === "function" && dependency) {
      cleanup();
    }
  }
  pervDependency.current = dependency || [];
};

export default useEffectCustomHook;

Create app.js file

import { useState } from "react";
import useEffectCustomHook from "../src/hooks/custom-use-effect.js";
import "./styles.css";

export default function App() {
  const [count, setCount] = useState(0);

  const incrementHandler = () => {
    setCount((count) => count + 1);
  };

  const decrementHandler = () => {
    setCount((count) => count - 1);
  };

  useEffectCustomHook(() => {
    console.log("Custome hook called...", count);

    return () => {
      console.log("code cleaned up done...");
    };
  }, [count]);

  return (
    <div className="App">
      <h1>Custom useEffect Hook</h1>
      <h2>Counter : {count}</h2>
      <button onClick={incrementHandler}>INC</button>
      <button onClick={decrementHandler}>DESC</button>
    </div>
  );
}
⚠️ **GitHub.com Fallback** ⚠️