I tried to find the same case, but everyone is in a different situation.
I've created 2 useEffects in my component, one for initializing the component (1 execution) and another to fetch data when some state (filter) changes. (many executions)
const [filter1, setFilter1] = useState({});
const [filter2, setFilter2] = useState({});
//initialize filters, only once
useEffect(() => {
//here i fetch all the data to fill the filter components.
setFilter1(data1);
setFilter2(data2);
}, []);
//everytime my filters change.
useEffect(() => {
//here i fetch data using the filter as parameters.
}, [filter1,filter2]);
The code above is my last approach and works fine. Every time I change the filters the useEffect fetch the data and load the table with that data.
I show below the old approach that I took, and the one I didn't like.
const loadData = useCallback((filter1,filter2) => {
//here i fetch data using the filter as parameters.
}, [filter1,filter2]);
useEffect(() => {
//here i fetch all the data to fill the filter components.
setFilter1(data1);
setFilter2(data2);
loadData(filter1, filter2);
},[]);
and I used the loadData function in every filter change handler like:
const onFilter1Change = (val) => {
setFilter1(val);
loadData(val, filter2)
};
The old approach above brought me some issues regarding how to use the hooks properly and that's why I find myself asking you React experts, how to improve my coding in the best way.
The new approach works fine for me, tho I wonder if it's right to use 2 useEffect in this case, or if there is a better way to do it.
Cheers
Where data1 & data2 comes from?
If it's a prop, and you are using a useEffect only to initialize them, you don't need a useEffect for that:
const [filter1, setFilter1] = useState(data1);
const [filter2, setFilter2] = useState(data2);
useEffect(() => {
//here i fetch data using the filter as parameters.
}, [filter1, filter2]);