Execute different code of useEffect's callback function on dependency changes

Viewed 121

A function fetchData() to be called as the component loads and also to be called whenever testA and testB prop to this component changes. And also when only testA prop changes I want to perform state update. Now the state update is happening when either testA and testB changes.

useEffect(()=>{
   fetchData();
   // Only When testA changes I want to update the below state.
   // setTableData([]);
},[testA, testB]);

If I use 2 useEffect I will be calling the fetchData twice on initial render. Which is not acceptable.

useEffect(()=>{
   fetchData();
   setTableData([]);
},[testA]);

useEffect(()=>{
   fetchData();
},[testB]);

How to achieve this functionality using hooks?

1 Answers

You might add a test to one of the hooks before calling fetchData to see if you're on the inital render or not. For example, if fetchData updates some data state, you could have data start out undefined and do:

useEffect(()=>{
   fetchData();
   setTableData([]);
},[testA]);

useEffect(()=>{
   if (data) {
       // then we're not on the initial render
       fetchData();
   }
},[testB]);

Or you could do the same sort of thing with a different stateful variable whose contents can be used to determine if you're on the initial render or not - it doesn't have to be data.

Related