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

230
Views
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
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!