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

231
Vistas
Avoiding code duplication in react functional components

I have n React functional components which share 90% of their content, but differ in a few functions they use.

Let's say my components are the following:

export default function BWPage(props) {
    const f = (x) => x+1
    const g = (x) => f(x)*2
    const h = (x) => g(x)*x
    return <div>{h(props.input)}</div>
}

export default function ColorPage(props) {
    const f = (x) => x+1
    const g = (x) => {props.setColor(f(x)); return 4;}
    const h = (x) => g(x)*x
    return <div>{h(props.input)}</div>
}

And so on. In OO programming I would obviously override the required function and be happy, but that isn't possible in React. The official guidelines say to use composition, but I don't see how that works here. Passing all functions that can be different as a prop is impractical as then g would be unable to call f. I also cannot create put all common functions somewhere else and import them, as then h isn't able to call g. What is the proper solution here?

about 4 years ago · Juan Pablo Isaza
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