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

210
Vistas
React, how to memoize API Data called in reusable component?

I have a component that opens the dialog to provide inputs:

function App() {
  const [toggle, setToggle] = useState(false);
  return (
    <>
      <button onClick={setToggle(true)}>Show Dialog</button>
    </>
  );
}

export default App;

This is the dialog component which is opened:

function Dialog() {

  return (
  <>
   <span>
     <div> Name: </div>
     <input type="text" />
   </span>
  <span>
     <div> Select: </div>
     <SelectionBox/>
   </span>
  </>
  );
}
export default Dialog;

Selection box component code is as following:

function SelectionBox() {
  const [value, setValue] = useState("");
  const [options, setOptions] = useState([]);
  const apiCalls = () => {
     service.getData1().then((data) => {
       service.getData2(data).then((opt) => {
         setOptions(opt);
       }).catch((e1) => {
         console.log(e1);
       });
     }).catch((e) => {
       console.log(e);
     });
     
  };

  return (
   <>
     <Select
      label="select"
      options={options}
      value={value} 
     />
   </>
  );

}
export default SelectionBox;

Selection box component calls two APIs to get and display the data in selection box. This API call takes time and I want to call the API only once when I open the dialog box and memoize that response for further dialog box actions. This select box can be re-used at some other place also and data is going to be same at all the places. How can I achieve this?

PS: I want to call the APIs when component is mounted. Also, not open to use any libraries.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can do that with the help of an useEffect and localStorage. On every mount, you check if there is saved data inside localStorage, if yes use it, else you call your api, and store the result inside localStorage. Something like so:

import { useEffect } from "react";
function SelectionBox() {
  const [value, setValue] = useState("");
  const [options, setOptions] = useState([]);

  useEffect(() => {
    const apiCalls = () => {
      service.getData1().then((data) => {
          service
            .getData2(data)
            .then((opt) => {
              localStorage.setItem("options", JSON.stringify(opt));
              setOptions(opt);
            })
            .catch((e1) => {
              console.log(e1);
            });
        })
        .catch((e) => {
          console.log(e);
        });
    };
    let opt;
    try {
      opt = JSON.parse(localStorage.getItem("options"));
    } catch (error) {
      console.log(error)
    }
    if (!Array.isArray(opt)) {
      apiCalls();
    } else {
      setOptions(opt);
    }
  }, []);

  return (
    <>
      <Select label="select" options={options} value={value} />
    </>
  );
}
export default SelectionBox;
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