Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda