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

140
Views
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 answers
Answer question

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 Report
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!