Skip to content

๐Ÿง  setMemo โ€‹

This guide explains how to use setMemo in SeraJS to create derived, memoized reactive values based on other signals.


๐Ÿ’ก What is setMemo? โ€‹

setMemo allows you to compute derived values from one or more signals. It automatically tracks signal dependencies and only recomputes the result when needed.

js
const result = setMemo(() => someSignal() + 1);
  • Returns a reactive getter function, similar to setSignal.
  • You can use the returned memo directly in JSX.

๐Ÿš€ Example App โ€‹

js
import { h, setSignal, Fragment, setMemo } from "serajs";

export default function App() {
  const [count, setCount] = setSignal(0);

  const Dabble = setMemo(() => count() * 2); // Doubles the count

  return (
    <Fragment>
      <h1>{() => count()}</h1>
      <button onClick={() => setCount(count() + 1)}>Increment Count</button>
      <button onClick={() => setCount(count() - 1)}>Decrement Count</button>
      <button onClick={() => setCount(0)}>Reset Count</button>
      <div>
        <h1>Dabble Count: {Dabble}</h1>
        {/* OR */}
        {/* <h1>Dabble Count: {() => Dabble()}</h1> */}
      </div>
    </Fragment>
  );
}

โœ… How to Use in JSX โ€‹

You can use a memoized value in JSX in two valid ways:

jsx
<h1>{() => Dabble()}</h1> // โœ… Valid - function form
<h1>{Dabble}</h1>         // โœ… Also valid - auto-evaluated

Both are fully reactive and update when their dependencies (like count) change.


๐Ÿง  Why Use setMemo? โ€‹

  • ๐Ÿš€ Efficient: Avoids unnecessary re-renders by caching results.
  • ๐Ÿงผ Clean: Separates derived logic from your main UI logic.
  • ๐Ÿ” Reactive: Tracks and updates automatically when dependencies change.

โš ๏ธ When to Use setMemo โ€‹

Use it when:

  • You need to compute a value based on other signals.
  • The derived value is used in multiple places.
  • You want to optimize performance.

๐Ÿงช Example Output โ€‹

CountDabble
00
12
24
36

๐Ÿ”„ Comparison โ€‹

ConceptDescription
setSignalBasic reactive value
setMemoDerived reactive value
setEffectSide-effect that runs on change

๐ŸŽ‰ Summary โ€‹

  • setMemo(() => derivedValue) gives you a cached, reactive function.
  • You can use it in JSX as {Dabble} or {() => Dabble()}.
  • Great for computed values that depend on signals.

Pager Previous page: setEffect