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

137
Vistas
React Functional Component - Where to store transformed value calculated from props

Let's say I have the following heavy calculation function:

function heavyCalculator(str:string):string{
  //Do some heavy calculation
  return result;
}
function SomeComponent({prop1,prop2,prop3,prop4}:Props){
  useEffect(()=>{
    const result = heavyCalculator(prop3);
    //How should i store the result?
  },[prop3])
  return <span>{resultFromHeavyCalculation}</span>;
}

How should I store the calculation result in a way that it won't get recalculated on every render / prop change?

Should I use "useMemo" or use "useState" and set it inside the "useEffect" only when prop3 is changed?

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

0

This is basically the prime use-case for useMemo. Although your approach with useEffect(() => ..., [prop3]) would also work if you store the result in a useState variable, useMemo would require less boilerplate:

function SomeComponent({prop1,prop2,prop3,prop4}:Props){
  const resultFromheavyCalculation = useMemo(() => heavyCalculator(prop3), [prop3])
  return <span>{resultFromHeavyCalculation}</span>;
}

You can learn more about useMemo in the official documentation. The example there is actually very similar to the one you're providing.

If you really set your mind on avoiding useMemo at all costs, the answer would be:

    function SomeComponent({prop1,prop2,prop3,prop4}:Props){
      const [resultFromHeavyCalculation, setResultFromHeavyCalculation] = useState();
      useEffect(()=>{
          const result = heavyCalculator(prop3);
          setResultFromHeavyCalculation(result);
      },[prop3]), [prop3])
      return <span>{resultFromHeavyCalculation}</span>;
    }
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