useMemo is a React Hook used to optimize performance by memoizing expensive calculations. In React Native, it helps prevent unnecessary re-computations during re-renders.
The useMemo hook takes two arguments: a function that returns a value and a dependency array.
// Basic syntax of useMemo
const memoizedValue = useMemo(() => {
return expensiveCalculation();
}, [dependency]);
// Optimizing expensive calculation using useMemo
import React, { useState, useMemo } from "react";
import { View, Text, Button } from "react-native";
export default function App() {
const [count, setCount] = useState(0);
const squaredValue = useMemo(() => {
return count * count;
}, [count]);
return (
<View>
<Text>Count: {count}</Text>
<Text>Squared: {squaredValue}</Text>
<Button title="Increase" onPress={() => setCount(count + 1)} />
</View>
);
}
When the button is pressed, the count updates. The squared value is recalculated only when count changes, not on every render.
Think of useMemo as caching a result. If dependencies don’t change, React reuses the cached value instead of recalculating it.
Try increasing the Count (dependency) vs toggling the Theme (unrelated state). Watch the Console log below to see when the calculation actually runs.