简体   繁体   中英

React hooks : useMemo and useEffect has a Missing dependency when we are trying to call a function

triggerData function is used in multiple functions. So, if i place the function inside the useEffect to avoid missing dependencies then i can not call the triggerData outside the useEffect ie, buildData .How can i avoid missing dependencies error?

useEffect(()=>{
 //api call
  if(something){
    triggerData(state, props);
  }
}[values]);

const triggerData = (state, props) => {
  return values + 1;
}

const buildData = () => {
  triggerData(state, props);
}

React Hook useEffect has a missing dependency: 'triggerData'. Either include it or remove the dependency array react-hooks/exhaustive-deps

When i add triggerData in the useEffect , i get the following error. triggerData was used before it was defined no-use-before-define

useEffect(()=>{
     //api call
      const triggerData = (values) => {
        return values + 1;
      }
      if(something){
        triggerData(values);
      }
    }[values, triggerData]);

    const buildData = () => {
      triggerData(values);
    }

If you are using triggerData only inside the hook, then i will prefer declaring the function inside the useEffect hook. Like:

useEffect(()=>{
  //api call
  const triggerData = (values) => {
     return values + 1;
  }
  if(something){
    triggerData(values);
  }
}, [values]);

You were missing something. You we declaring triggerData inside the hook and also passing it to useEffect that's why it complains about function already declared.

In case you really want to declare triggerData outside useEffect to use it somewhere else you can do it like this:

useEffect(()=>{
 //api call
  if(something){
    triggerData(state, props);
  }
}, [values, triggerData]);

const triggerData = useCallback((state, props) => {
  return values + 1;
}, [state, props]);


const buildData = () => {
  triggerData(state, props);
}

In use useCallback provide the accurate params to get it invoked minimal according to the scenario. Let say, you are accessing value from state in triggerData . Then you can pass state.value rather than the whole state .

Hope this works for you.

If you want to use triggerData outside of useEffect you can use another hook called useCallback.

You don't need to pass props and state to function as it will be available from the parent's scope.

const triggerData = useCallback(() => {
  return values + 1;
}, [ /* pass required depedencies here */])

useEffect(()=>{
 //api call
  if(something){
    triggerData(); // don't pass state and props here
  }
}[values, triggerData]);

const buildData = () => {
  triggerData(); // dont pass state and props here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM