Analogy of Lazy loading and Memoization | React | Part 2
Pranav Bakare
Posted on November 24, 2024
Analogy to explain lazy loading and memoization in React:
Lazy Loading Analogy
Imagine you are moving into a new house. You own a lot of furniture, but instead of bringing everything at once, you decide to move only the furniture that’s immediately needed. For example:
You first bring the bed for sleeping.
Later, when you’re ready to set up the living room, you bring the sofa.
Key Idea: "Don’t bring things until they’re actually required."
React Context: In React, React.lazy works the same way. It loads a component (like furniture) only when it’s actually needed on the screen.
Example in React: A dashboard where detailed charts are only loaded when you open a specific tab.
Memoization Analogy
Now imagine you are calculating the cost of groceries. Normally, you write down the total cost each time you shop.
One day, you notice you’re buying the same items every week.
So, you save last week’s total in a notebook.
Next time, if your shopping list hasn’t changed, you just refer to the saved total instead of recalculating it.
Key Idea: "Save the result of a previous calculation and reuse it if the input hasn’t changed."
React Context: useMemo and React.memo behave like the notebook, caching expensive calculations or rendering results.
Example in React: A component displaying a list of sorted items. If the list hasn’t changed, the sorting logic doesn’t run again.
Comparison with Analogies
Summary Analogy:
Lazy Loading: "Don’t carry what you don’t need yet."
Memoization: "Don’t redo what you already figured out."
Posted on November 24, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024