Optimize App Performance Using useMemo

What is useMemo?

useMemo is a hook in react-native that will return the memorized value. 

The most common advantage to use the useMemo is to optimize the performance of the react-native application.

How it works?

The useMemo will takes two arguments. In the first argument, you have to pass the function and in the second argument, you have to pass the array of dependencies. 

useMemo will recompute the memorized values once one of the dependencies has changed.

Whenever the state is changed in the react-native the component re-render itself. In react-native some-times, we have functions that have expensive calculations code. Once the state has updated the react-native component will call the render and the function will be called again and do the calculation even if the state has no effect on that method. Using useMemo we can resolve the above issue.

Impact of useMemo in application performance

Using useMemo you can avoid expensive calculations on every render, Which will help you to boost your application performance and avoid unnecessarily re-calculation. 

Syntax

const memoizedValue = useMemo(() => functionName(), [dependencie]);

If one of the values of dependency change then only the new value will be computed.

const memoizedValue = useMemo(() => functionName());

If you did not define the dependencies then the value will be computed on every render and not be memorized.

Let's check with an example.

In the below example we have a silk material. I have added one button using which user can increment the price by 5%.  The tax and basic is calculated once the amount of material is changed. Their is another button using which you can incremet the lot number.

const App: () => React$Node = () => {
  const [amount, setAmount] = React.useState(50);
  const [name, setName] = React.useState('Silk');
  const [meter, setMeter] = React.useState(200);
  const [lotNumber, setLotNumber] = React.useState(1);

  const ShowProfile = () => {
    console.log('Material Info');
    return (
      <View>
        <Text>Name : {name}</Text>
        <Text>Quantity(Meter) : {meter}</Text>
        <Text>Lot Number : {lotNumber}</Text>
      </View>
    );
  };

  const calculateAmount = (amount) => {
    console.log('Calculate Amount');
    let basic = amount * meter;
    let tax = (amount * 5) / 100;
    let total = basic + tax;
    return [basic, tax, total];
  };

  const incrementAmount = () => {
    let incrementedAmount = amount + (amount * 5) / 100;
    setAmount(incrementedAmount);
  };

  const incrementLotNumber = () => {
    console.log('IncrementLotNumber');
    setLotNumber(lotNumber + 1);
  };

  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ShowProfile />
        <Text>Basic : {calculateAmount(amount)[0]}</Text>
        <Text>Tax : {calculateAmount(amount)[1]}</Text>
        <Text>Total : {calculateAmount(amount)[2]}</Text>
        <Button title={'Increment amount by 5%'} onPress={incrementAmount} />
        <Button title={'Increment Lot Number'} onPress={incrementLotNumber} />
      </SafeAreaView>
    </>
  );
};

With the above code, If you hit the Increment Lot Number button then the calculateAmount will also called even if you have not changed the price of the material. The calculation will occur on each render.

To check the result, I have put the log and you can see the log result below.

useMemo

To resolved the above use you have to use the useMemo and memorized the value. For that you have to create the memorizedValue and use that value.

const MemorizedValue = React.useMemo(() => calculateAmount(amount), [amount]);

 return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ShowProfile />
        <Text>Basic : {MemorizedValue[0]}</Text>
        <Text>Tax : {MemorizedValue[1]}</Text>
        <Text>Total : {MemorizedValue[2]}</Text>
        <Button title={'Increment amount by 5%'} onPress={incrementAmount} />
        <Button title={'Increment Lot Number'} onPress={incrementLotNumber} />
      </SafeAreaView>
    </>
  );

Now, If you hit the incrementLotNumber then the price calculation will not happen because the calculation is not depend upon the lot number.

useMemo




The calculation will only occur if you changed the price. To change the price you can press the incrementAmount button.

useMemo



Conclusion

You can use the useMemo for the a performance optimization. If your component have very expensive calculation then you have to use the useMemo. 

There are several case for example to free memory for offscreen components where the useMemo will forgot the memorized value so to prevent the failure of your application you have to verify that your code is working as expected without the useMemo.

 

Comments