0
0
React Nativemobile~15 mins

React.memo and useMemo in React Native - Deep Dive

Choose your learning style9 modes available
Overview - React.memo and useMemo
What is it?
React.memo and useMemo are tools in React Native that help your app run faster by remembering things it has already done. React.memo is used to keep a whole component from redoing its work if its inputs haven't changed. useMemo is a hook that remembers the result of a calculation so it doesn't have to do it again unless something important changes. Both help avoid unnecessary work and make your app smoother.
Why it matters
Without React.memo and useMemo, your app might waste time and battery by doing the same work over and over, even when nothing has changed. This can make your app feel slow or laggy, especially on phones with less power. Using these tools helps your app stay quick and responsive, giving users a better experience and saving device resources.
Where it fits
Before learning React.memo and useMemo, you should understand basic React Native components, props, state, and hooks. After mastering these tools, you can explore advanced performance optimization techniques like useCallback, virtualization, and profiling React Native apps.
Mental Model
Core Idea
React.memo and useMemo remember previous results to skip repeating work when inputs stay the same.
Think of it like...
It's like writing a note to remember a math answer so you don't have to solve the problem again every time someone asks.
┌───────────────┐       ┌───────────────┐
│ Component A   │       │ Component B   │
│ (props: X)   │──────▶│ React.memo    │
│               │       │ Checks props  │
└───────────────┘       │ If same, skip │
                        │ re-render     │
                        └───────────────┘

┌───────────────┐
│ useMemo Hook  │
│ Input: deps   │
│ If deps same  │
│ Return cached │
│ value        │
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding React Component Re-rendering
🤔
Concept: React components re-run their code when their inputs or state change.
In React Native, every time a component's props or state change, React runs the component function again to update the UI. This is called re-rendering. Even if the output looks the same, React still does the work of running the function.
Result
Your app updates the screen to match the latest data, but sometimes it does extra work that isn't needed.
Understanding that React re-runs components helps you see why avoiding unnecessary re-renders can speed up your app.
2
FoundationProps and State Trigger Re-renders
🤔
Concept: Changes in props or state cause React components to re-render.
When a parent component passes new props to a child, or when a component changes its own state, React schedules that component to re-render. This means the component function runs again, updating the UI.
Result
The UI stays in sync with data changes, but frequent changes can cause many re-renders.
Knowing what triggers re-renders helps you identify when to optimize your components.
3
IntermediateReact.memo Prevents Unneeded Re-renders
🤔Before reading on: do you think React.memo stops all re-renders or only some? Commit to your answer.
Concept: React.memo wraps a component and skips re-rendering it if its props haven't changed.
React.memo is a higher-order component that compares the current props with the previous props. If they are the same (shallow comparison), React skips running the component function again, saving time.
Result
Components wrapped in React.memo only re-render when their props change, reducing unnecessary work.
Understanding React.memo helps you control when components update, improving app performance.
4
IntermediateuseMemo Caches Expensive Calculations
🤔Before reading on: do you think useMemo runs its calculation every render or only when dependencies change? Commit to your answer.
Concept: useMemo remembers the result of a calculation and only recalculates it when its dependencies change.
useMemo is a React hook that takes a function and a list of dependencies. It runs the function once and saves the result. On later renders, if the dependencies are the same, it returns the saved result instead of running the function again.
Result
Expensive calculations inside useMemo run only when needed, making your app faster.
Knowing how useMemo caches results helps you avoid slow calculations on every render.
5
IntermediateShallow Comparison Limits React.memo Effectiveness
🤔Before reading on: do you think React.memo deeply compares objects or only checks references? Commit to your answer.
Concept: React.memo uses shallow comparison, so it only checks if prop references changed, not their contents.
React.memo compares previous and new props by checking if their references are the same. For objects or arrays, even if contents are equal but the reference is different, React.memo treats them as changed and re-renders.
Result
React.memo may not prevent re-renders if you pass new object or array props each time.
Understanding shallow comparison helps you avoid common pitfalls with React.memo.
6
AdvancedCombining React.memo and useMemo for Performance
🤔Before reading on: do you think combining React.memo and useMemo can reduce both re-renders and recalculations? Commit to your answer.
Concept: Using React.memo to avoid re-renders and useMemo to cache calculations together maximizes performance gains.
Wrap components with React.memo to skip re-renders when props don't change. Inside those components, use useMemo to cache expensive calculations or derived data. This combination reduces both unnecessary component runs and slow computations.
Result
Your app runs fewer component functions and fewer heavy calculations, improving speed and battery life.
Knowing how to combine these tools lets you build highly efficient React Native apps.
7
ExpertPitfalls and Subtleties of Memoization in React
🤔Before reading on: do you think overusing React.memo and useMemo always improves performance? Commit to your answer.
Concept: Memoization has costs and can sometimes hurt performance if used without care.
React.memo and useMemo add memory overhead and extra comparison work. If your components or calculations are cheap, memoization can slow things down. Also, stale closures or incorrect dependencies in useMemo can cause bugs or outdated data.
Result
Using memoization wisely requires balancing costs and benefits and understanding React's rendering behavior deeply.
Understanding memoization tradeoffs prevents common mistakes and helps you optimize only where it truly matters.
Under the Hood
React.memo works by wrapping a component and intercepting its props before rendering. It performs a shallow comparison of previous and new props. If they match, React skips calling the component function and reuses the last rendered output. useMemo stores the result of a function call along with its dependencies in React's internal hook state. On subsequent renders, React compares dependencies; if unchanged, it returns the cached result instead of recalculating.
Why designed this way?
React was designed to re-run components on every render for simplicity and correctness. Memoization tools like React.memo and useMemo were added later to optimize performance without changing React's core model. Shallow comparison was chosen for speed and simplicity, avoiding deep, costly checks. This design balances ease of use with performance gains, letting developers opt-in to memoization where needed.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Parent Render │──────▶│ React.memo    │──────▶│ Compare Props │
└───────────────┘       └───────────────┘       └───────────────┘
                                                      │
                                                      ▼
                                            ┌───────────────────┐
                                            │ Props Same?       │
                                            │ Yes: Skip Render  │
                                            │ No: Render Comp   │
                                            └───────────────────┘

┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Component Run │──────▶│ useMemo Hook  │──────▶│ Check Deps    │
└───────────────┘       └───────────────┘       └───────────────┘
                                                      │
                                                      ▼
                                            ┌───────────────────┐
                                            │ Deps Same?        │
                                            │ Yes: Return Cache │
                                            │ No: Recompute     │
                                            └───────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does React.memo prevent re-renders even if props change? Commit yes or no.
Common Belief:React.memo stops all re-renders no matter what.
Tap to reveal reality
Reality:React.memo only skips re-renders if props are shallowly equal; if props change, it re-renders.
Why it matters:Believing React.memo blocks all re-renders can lead to bugs when components don't update as expected.
Quick: Does useMemo guarantee your function runs only once ever? Commit yes or no.
Common Belief:useMemo runs the function only once and never again.
Tap to reveal reality
Reality:useMemo runs the function again whenever its dependencies change.
Why it matters:Misunderstanding this can cause stale data or missed updates in your app.
Quick: Does React.memo deeply compare nested objects in props? Commit yes or no.
Common Belief:React.memo deeply compares objects and arrays in props to decide re-rendering.
Tap to reveal reality
Reality:React.memo only does shallow comparison, so new object or array references cause re-renders even if contents are equal.
Why it matters:This can cause unexpected re-renders and performance issues if you pass new objects each time.
Quick: Does overusing React.memo and useMemo always improve app speed? Commit yes or no.
Common Belief:Using React.memo and useMemo everywhere always makes your app faster.
Tap to reveal reality
Reality:Overusing memoization can add overhead and slow down your app if used on cheap components or calculations.
Why it matters:Blindly adding memoization can hurt performance and increase complexity.
Expert Zone
1
React.memo's shallow comparison only checks prop references, so stable references (like useCallback or useMemo) are often needed to prevent re-renders.
2
useMemo caches results per component instance and per render cycle, so it doesn't share cached values across different components or app runs.
3
Incorrect dependency arrays in useMemo can cause subtle bugs like stale closures or missed updates, which are hard to debug.
When NOT to use
Avoid React.memo and useMemo for very simple components or cheap calculations where memoization overhead outweighs benefits. Instead, rely on React's default rendering. For deep object comparisons, consider custom comparison functions or immutable data structures. When you need to memoize callbacks, use useCallback instead.
Production Patterns
In real apps, React.memo is often used on list item components to prevent re-renders when list data doesn't change. useMemo caches filtered or sorted data derived from props or state. Developers combine React.memo with useCallback to keep prop references stable. Profiling tools help identify which components benefit most from memoization.
Connections
Caching in Web Browsers
Both cache results to avoid repeating expensive work.
Understanding browser caching helps grasp why React.memo and useMemo store previous results to speed up rendering.
Functional Programming Memoization
React.memo and useMemo are specialized forms of memoization from functional programming.
Knowing general memoization concepts clarifies how React optimizes repeated function calls.
Human Memory Recall
Both rely on remembering past results to avoid redoing work.
Recognizing this similarity helps appreciate why remembering previous outputs saves time and effort.
Common Pitfalls
#1Wrapping every component with React.memo regardless of cost.
Wrong approach:const MyComponent = React.memo(function(props) { return {props.text}; });
Correct approach:Use React.memo only on components that re-render often and have expensive rendering logic.
Root cause:Assuming memoization always improves performance without measuring.
#2Passing new object or array literals as props causing React.memo to fail.
Wrong approach:
Correct approach:const data = useMemo(() => ({id: 1}), []);
Root cause:Not realizing React.memo does shallow comparison and new objects have new references.
#3Leaving out dependencies in useMemo causing stale values.
Wrong approach:const value = useMemo(() => computeExpensive(a, b), []);
Correct approach:const value = useMemo(() => computeExpensive(a, b), [a, b]);
Root cause:Misunderstanding how dependency arrays control when useMemo recalculates.
Key Takeaways
React.memo and useMemo help React Native apps run faster by remembering previous results and skipping unnecessary work.
React.memo prevents component re-renders when props are shallowly equal, but new object references can still cause re-renders.
useMemo caches expensive calculations and only recalculates when its dependencies change, avoiding repeated slow work.
Memoization has costs and should be used thoughtfully; overusing it can hurt performance and cause bugs.
Combining React.memo and useMemo strategically improves app responsiveness and battery life, especially in complex or large apps.