0

I have write a custome hook to prevent any not usefull updateds in data that useEffect triggered with them (like when I send an object in useEffect dependencies that cause useEffect to trigger every time or when send an object to useEffect but the layered data in object have been changed but useEffect cant detect them and dont do anything)

export const useUpdateEffect = (callback, dependencies) => {

  const previousDeps = useRef(null);

  useEffect(() => {
    const haveChange = JSON.stringify(dependencies) === JSON.stringify(previousDeps.current)
    if (haveChange) return;

    const returnCallback = callback(previousDeps.current);

    return () => {

      if (typeIs(returnCallback, "Function")) {
        returnCallback();
      }

      previousDeps.current = dependencies;
    }
  }, [callback, dependencies])
}

If you can see this hook do its job when dependencies have been changed (with any layer). also this hook saves the depenedencies and use them to compare with current one. (like componentDidUpdate).

but the problem on this code is that when I try to send a clean method with return. the clean method call imediately after useEffect body works.

I need to know what is the problem in this hook. to see the problem try following code with useUpdateEffect and see the problem what I mean. https://stackoverflow.com/a/53090848/6737576

hadi karami
  • 13
  • 1
  • 3
  • 1
    If you stay immutable and not create a new object on every render, all of this should not be needed, right? – Domino987 Mar 25 '20 at 11:37
  • You just replaced the shallowing comparison of dep array in the useEffect to string comparison – Dennis Vash Mar 25 '20 at 12:05
  • I just want a functinality like `componentDidUpdate`. but useEffect just runs on shallow comparison and can't see changes on dep or changes on a immutable things. On the other side when I want to have a state that useEffect and others can change it and also this useEffect should check it to found changes to do something on that state I should use something like my `useUpdateEffect` to be sure about changes on any dep. – hadi karami Mar 25 '20 at 20:05

0 Answers0