Memos

A derived function runs every time it is called. That is usually fine, but when several places read the same result, each read repeats the work.

createMemo runs the calculation once per change and shares the result with every reader:

const filtered = createMemo(() =>
products.filter((product) => product.name.includes(query()))
);

The search below filters 2,000 products and reads the result in three places. The console.log call is only there to make each run visible; a real calculation should not log or write state.

A memo also stops updates that change nothing. When its new result equals the old one, its readers are not notified.

Try it: type a letter and watch the "filter run" logs in the console: three per keystroke. Wrap the calculation in createMemo, type again, and the count drops to one.

Loading editor…