Home > Blockchain >  React custom hook runs useEffect multiple time
React custom hook runs useEffect multiple time

Time:04-12

I have a custom hook that only have useEffects and returns null. I am using it in App.js file. But now i have to return a function and import that custom hook some in other component. But when i call that custom hook in another component. useEffects run too (cause multiple times and that is the problem). But i only need them to run once in App.js file.

I solve this with this if statement. I pass isApp true in App.js and i don't in other component. But is there some other way to solve that. I didn't like that approach

useEffect(() => {
    if (!props?.isApp)
        return;

    func();
}, [
    someDependencies
]);

CodePudding user response:

useEffect(callback, dependencies) is the hook that manages the side-effects in functional components. The callback argument is a function to put the side-effect logic. dependencies is a list of dependencies of your side-effect: being props or state values.

useEffect(callback, dependencies) invokes the callback after initial mounting, and on later renderings, if any value inside dependencies has changed.

If you change one of the dependencies, the effect function will be executed. If you change a dependency in the effect function you will have an infinite loop.

CodePudding user response:

a. If you only want to run once!

useEffect(() =>{ func(); }, []);

b. If you want to run once based on deps.

function useCall(callback, condition = true) {
  const ref = React.useRef(false);

  React.useEffect(() => {
    if (condition && !ref.current) {
      ref.current = true;
      callback();
    }
  }, [callback, condition]);
}

useCall(()=>{ }, isCondition);
  • Related