Skip to main content

AtomOptions

The AtomOptions<T> type defines configuration options that can be passed when creating an atom to customize its behavior.

Type Definition

Properties

compare

A custom comparison function to determine if the atom’s value has changed. This function is called when setting a new value to decide whether subscribers should be notified. Type:
Optional: Yes Default behavior: If not provided, atoms use reference equality (===) to compare values. Returns:
  • true if the values are considered equal (no change, don’t notify subscribers)
  • false if the values are different (notify subscribers)

Usage Examples

Default comparison (reference equality)

Custom deep equality comparison

Shallow comparison for objects

Numeric tolerance comparison

Custom comparison for arrays

Always notify (no comparison)

Conditional comparison logic

Performance optimization with compare

When to Use Custom Comparison

Use custom comparison when:
  1. Object values: You store objects and want to compare by content, not reference
  2. Performance: You want to avoid unnecessary re-renders or updates
  3. Tolerance: You need approximate equality (e.g., floating-point numbers)
  4. Partial comparison: Only certain fields matter for determining changes
  5. Always notify: You want every set call to notify subscribers regardless of value

Best Practices

  1. Keep it fast: Comparison functions are called on every set, so keep them efficient
  2. Be consistent: Ensure your comparison logic is symmetric and transitive
  3. Consider immutability: If you use immutable updates, default reference equality might be sufficient
  4. Document behavior: If using custom comparison, document why and how it works
  • Atom - The writable atom type that accepts options
  • ReadonlyAtom - Read-only atoms also support comparison options