Skip to content

Ref

A Ref<A> is a mutable cell holding an immutable value A behind atomic, pure updates. Every read and write is an Effect, so concurrent fibers share one reference without lost updates.

Atomic Ref vs. reactive SubscriptionRefAtomic Ref vs. reactive SubscriptionRef
Atomic Ref vs. reactive SubscriptionRef
Reference typeUpdate callbackPublishes change stream?Use when
RefPure, synchronousNoFast counters, caches, in-memory state
SynchronizedRefEffectful (serialized)NoNext state depends on current state + async/service work
SubscriptionRefPure or effectfulYes (Stream)Observers need current snapshot plus live updates

Creating a shared reference

effect function makeCounter() {
  return try Ref.make(0)
}
// Ref.Ref<number>!!
 
effect function countLocally() {
  const counter = try makeCounter()
  try Ref.update(counter, (n) => n + 1)
  return try Ref.get(counter)
}
// Run in an effect function:
//   {
//     const jsonValue = [try countLocally(), try countLocally()]
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
// Output: [1,1]

Ref.make(initial) returns an Effect that allocates a fresh cell each time it runs. Calling try makeCounter() twice creates two independent counters; to share state across callers, pass the same Ref handle (or store it in a service layer).

Reading and atomically updating state

effect function allocateIds() {
  const nextId = try Ref.make(100)
  const first = try Ref.modify(nextId, (n) => [n, n + 1] as const)
  const second = try Ref.getAndUpdate(nextId, (n) => n + 1)
  const current = try Ref.get(nextId)
  try Ref.set(nextId, 500)
  return { first, second, current }
}
// Returns { first: 100, second: 101, current: 102 }.
// Run in an effect function:
//   {
//     const jsonValue = try allocateIds()
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
// Output: {"first":100,"second":101,"current":102}

Ref.modify computes [result, nextState] in one atomic step, returning result while storing nextState. getAndUpdate returns the previous value; updateAndGet returns the new value. Never split a read-modify-write into separate Ref.get and Ref.set calls—another fiber can interleave between them.

Coordinating concurrent updates

effect function countCompleted() {
  const completed = try Ref.make(0)
  for concurrent(4) (const delay of [10, 20, 30, 40]) {
    try sleep(`${delay} millis`)
    try Ref.update(completed, (n) => n + 1)
  }
  return try Ref.get(completed) // 4
}
// Run in an effect function: try Console.log(try countCompleted())
// Output: 4

Each Ref.update reads the latest value and writes its replacement atomically, so all four increments survive. Because Ref.update callbacks must be pure and synchronous, always return a fresh array or object rather than mutating in place. If computing the next state requires awaiting a service or sleeping, switch to SynchronizedRef.updateEffect.

Supplying state as a service

service RequestCount {
  increment(): void!!
  read(): number!!
}
 
const RequestCountLive = Layer.effect(RequestCount, effect {
  const count = try Ref.make(0)
  return {
    increment: () => Ref.update(count, (n) => n + 1),
    read: () => Ref.get(count)
  }
})
 
effect function handleRequests() {
  provide RequestCountLive {
    const requests = try RequestCount
    try requests.increment()
    try requests.increment()
    return try requests.read()
  }
}
// Run in an effect function:
//   {
//     const jsonValue = [try handleRequests(), try handleRequests()]
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
// Output: [2,2]

Building RequestCountLive allocates one Ref shared by every consumer within the same provide block (or ManagedRuntime); a separate provide constructs an independent instance. Wrapping the Ref behind service methods hides the cell handle so callers can only perform permitted transitions.

Sharing references across fibers

effect function collectNames() {
  return try scoped(effect {
    const names = try Ref.make<ReadonlyArray<string>>([])
    const west = fork.scoped effect {
      try sleep("20 millis")
      try Ref.update(names, (old) => [...old, "west"])
    }
    const east = fork Ref.update(names, (old) => [...old, "east"])
    join west
    join east
    return try Ref.get(names)
  })
}
// Run in an effect function:
//   {
//     const jsonValue = (try collectNames()).toSorted()
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
// Output: ["east","west"]

Forked closures share the Ref handle itself, not a snapshot of its value. Joining both fibers ensures all updates finish before the final Ref.get; update order still depends on fiber scheduling.

Coming from Effect

Ref.make, Ref.get, and every update combinator return Effect values—run them with try in effect code. Methods that forward an Effect directly (such as () => Ref.get(count)) can remain plain arrow functions.


The matching Effect page: effect.website/docs/v4/state-management/ref