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

Viewed 129

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?

1 Answers

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>;
    }
Related