Memos
Compute values efficiently with createMemo
.
createMemo
is a feature in Olova that allows you to compute derived values efficiently. It ensures that the computation is only re-executed when its dependencies change, which can help optimize performance in your application.
Here's a practical example using createMemo
:
jsx
import { createSignal, createMemo } from "olova";
function ShoppingCart() {
const [price, setPrice] = createSignal(10);
const [quantity, setQuantity] = createSignal(2);
// Memo to compute the total cost
const total = createMemo(() => price() * quantity());
return (
<div>
<h1>Total Cost: ${total()}</h1>
<button onClick={() => setPrice(price() + 5)}>Increase Price</button>
<button onClick={() => setQuantity(quantity() + 1)}>
Increase Quantity
</button>
</div>
);
}
export default ShoppingCart;
Explanation
- Importing
createMemo
: We importcreateMemo
fromolova
to compute derived values. - Creating Signals: We use
createSignal
to manage theprice
andquantity
states. - Using
createMemo
: ThecreateMemo
function computes the total cost based on the currentprice
andquantity
. It only recalculates when these dependencies change. - Rendering the UI: The component displays the total cost and provides buttons to increase the price and quantity, demonstrating how the memoized value updates efficiently.
This example shows how createMemo
can be used to efficiently compute values in response to state changes in Olova, optimizing performance by avoiding unnecessary recalculations.
jsx
const [price, setPrice] = createSignal(10);
const [quantity, setQuantity] = createSignal(2);
const total = createMemo(() => price() * quantity());
console.log(total()); // 20