0
0
React Nativemobile~7 mins

React.memo and useMemo in React Native

Choose your learning style9 modes available
Introduction

React.memo and useMemo help your app run faster by remembering things so it doesn't do extra work.

When you have a component that shows the same thing many times and doesn't need to change often.
When you want to avoid re-calculating a value that takes time unless something important changes.
When your app feels slow because it keeps re-rendering parts that look the same.
When you pass big objects or functions to child components and want to stop them from re-rendering unnecessarily.
Syntax
React Native
const MemoizedComponent = React.memo(Component);

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

React.memo wraps a component to remember its last output and skip re-render if props are the same.

useMemo remembers a value from a function and only recalculates it when dependencies change.

Examples
This component will only re-render if the name prop changes.
React Native
const Greeting = React.memo(({ name }) => {
  return <Text>Hello, {name}!</Text>;
});
This calculates the sum of numbers only when the numbers array changes.
React Native
const total = useMemo(() => numbers.reduce((a, b) => a + b, 0), [numbers]);
Sample App

This app shows a count and its doubled value. The CountDisplay component only re-renders when count changes because it is wrapped with React.memo. The doubled value is calculated only when count changes using useMemo. Toggling the other state does not cause CountDisplay to re-render.

React Native
import React, { useState, useMemo } from 'react';
import { View, Text, Button } from 'react-native';

const CountDisplay = React.memo(({ count }) => {
  console.log('CountDisplay rendered');
  return <Text>Count: {count}</Text>;
});

export default function App() {
  const [count, setCount] = useState(0);
  const [other, setOther] = useState(false);

  const doubled = useMemo(() => {
    console.log('Calculating doubled');
    return count * 2;
  }, [count]);

  return (
    <View style={{ padding: 20 }}>
      <CountDisplay count={count} />
      <Text>Doubled: {doubled}</Text>
      <Button title="Increase Count" onPress={() => setCount(count + 1)} />
      <Button title="Toggle Other" onPress={() => setOther(!other)} />
    </View>
  );
}
OutputSuccess
Important Notes

React.memo only works for functional components.

useMemo should be used for expensive calculations, not for every value.

Console logs help you see when components or calculations run.

Summary

React.memo remembers a component's output and skips re-render if props are unchanged.

useMemo remembers a calculated value and only recalculates when dependencies change.

Both help improve app speed by avoiding unnecessary work.