← Back to Chapters

useMemo Hook

⚡ useMemo Hook

? Quick Overview

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.

? Key Concepts

  • Returns a memoized value
  • Re-computes only when dependencies change
  • Improves rendering performance
  • Does NOT prevent re-rendering

? Syntax / Theory

The useMemo hook takes two arguments: a function that returns a value and a dependency array.

? View Code Example
// Basic syntax of useMemo
const memoizedValue = useMemo(() => {
return expensiveCalculation();
}, [dependency]);

? Code Example

? View Code Example
// 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>
);
}

? Live Output / Explanation

When the button is pressed, the count updates. The squared value is recalculated only when count changes, not on every render.

? Interactive Explanation

Think of useMemo as caching a result. If dependencies don’t change, React reuses the cached value instead of recalculating it.

?️ Interactive Simulation

Try increasing the Count (dependency) vs toggling the Theme (unrelated state). Watch the Console log below to see when the calculation actually runs.

Current Count 0
Squared Value (Memoized) 0
> Waiting for interaction...

? Use Cases

  • Heavy calculations
  • Derived data from props or state
  • Optimizing lists and filters
  • Improving UI responsiveness

✅ Tips & Best Practices

  • Use only for expensive calculations
  • Avoid overusing for simple values
  • Always provide correct dependencies

? Try It Yourself

  • Add a console log inside useMemo and observe renders
  • Remove dependency array and notice recalculations
  • Compare behavior with and without useMemo