Before we get to memoization we need to talk about caching. Like most concepts in programming we can use a box analogy. Caching in simplest terms is putting data in an easily accessible box to speed up our code by keeping a fast record of it on hand. Memoization is a special way of caching that is commonly used in dynamic programming and in our case React. To state it more clearly memoization is a caching a return value (data in our box) from a past function to solve a problem so you don't have to calculate it again.
It is but one of the many optimization techniques out there. In the beginning it may not seem like a big deal but as functions grow in size and complexity, their calculations can be more expensive to run. A code snippet for demonstration purposes:
const cache = {};
const factorial = n => {
if (cache[n]) {
return cache[n];
}
let value;
if (n === 0) value = 1;
else value = (factorial(n - 1) * n);
cache[n] = value;
return value;
};
When it comes to React Web Applications, we can look at through the lens of the example of a dropdown menu component. Using libraries like 'reselect' we can avoid re-rendering the component if the value of the state doesn't change.
Though in this case it's a bit misleading because in my items cart redux is running a shallow equality check to see if the values were the same to try to save us a re-render. We're memoizing the transformation logic being ran through our 'mapStateToProps' with creating selectors and createStructuredSelector from 'reselect's library though. As you can see with some of the example code snippet here:
const CartDropdown = ({ cartItems }) => (
<div className="cart__dropdown">
<div className="cart__items">
{cartItems.length ? (
cartItems.map((cartItem) => (
<CartItem key={cartItem.id} item={cartItem} />
))
) : (
<span className="empty__message">Your cart is empty</span>
)}
</div>
<CustomButton>GO TO CHECKOUT</CustomButton>
</div>
);
const mapStateToProps = createStructuredSelector({
cartItems: selectCartItems,
});
export default connect(mapStateToProps)(CartDropdown);
It is something to keep in mind as you grow in your developing journey as it can cut down tremendously on your code refactoring.
If you want to take a look at the whole project to get a better high level idea you can see it Here on my Github