Effect.ts: Absence as First-Class
State Management • Lesson 48 of 51
29. Ref: Basic Operations
make, get, and set - the three fundamental Ref operations
The Three Basics
const program = Effect.gen(function* () {
// 1. make: Create a Ref
const counter = yield* Ref.make(0);
// 2. get: Read current value
const value1 = yield* Ref.get(counter); // 0
// 3. set: Write new value
yield* Ref.set(counter, 42);
const value2 = yield* Ref.get(counter); // 42
return value2;
});
Understanding Each Operation
Ref.make(initialValue)
Creates a new Ref with an initial value.
const counter = yield* Ref.make(0); // number Ref
const name = yield* Ref.make("Alice"); // string Ref
const items = yield* Ref.make([1,2,3]); // array Ref
Returns: Effect<Ref<T>, never, never>
- You get back an Effect that produces a Ref
- The Ref is a handle to mutable state
Ref.get(ref)
Reads the current value from a Ref.
const value = yield* Ref.get(counter);
// value is the actual number, not a Ref!
Returns: Effect<T, never, never>
- You get back the value, not the Ref
- Safe to use like any other value
Ref.set(ref, newValue)
Replaces the entire value.
yield* Ref.set(counter, 100);
// counter is now 100, regardless of what it was before
Returns: Effect<void, never, never>
- Just performs the update
- No return value needed
Example: Score Tracker
const game = Effect.gen(function* () {
const score = yield* Ref.make(0);
console.log(yield* Ref.get(score)); // 0
yield* Ref.set(score, 10); // Player scored!
console.log(yield* Ref.get(score)); // 10
yield* Ref.set(score, 25); // Scored again!
console.log(yield* Ref.get(score)); // 25
});
Key Insight
Think of Ref like a box:
Ref.make(): Create an empty box with initial contentsRef.get(): Look inside the boxRef.set(): Replace the contents of the box
All three operations return Effects, so they compose with everything else in Effect!
The foundation: make, get, and set
Part 48 of 51 in the Effect.ts Absence Modeling series