Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
is a good approach defining 2 useEffect Hooks, see my use of case bellow

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!