TSone

Reactive API

This page documents the TSone reactive system API.

Core Function Overview

NameSignatureDescription
reactivereactive<T extends object>(target: T): TCreates a reactive proxy object.
effecteffect(fn: () => void, options?): EffectRunnerCreates an effect that reruns when its dependencies change.
computedcomputed<T>(getter: () => T): { value: T }Creates a cached computed value.
refref<T>(value: T): { value: T }Creates a reactive reference for a single value.
isRefisRef(value: unknown): booleanChecks whether a value is a ref.
unrefunref<T>(value: T | Ref<T>): TReturns value for a ref, or returns the original value otherwise.
readonlyreadonly<T extends object>(target: T): TCreates a readonly reactive proxy object.
stopstop(effect: EffectRunner): voidStops an effect from responding to further updates.
nextTicknextTick(): Promise<void>Resolves after the current batch of reactive effects (component re-renders) finishes. Use it when you need to read the latest DOM after changing state.
flushSyncflushSync(): voidSynchronously flushes pending reactive effects and completes component re-renders immediately. Mostly useful in tests or when reading the DOM synchronously.
watchwatch(source, callback, options?): () => voidWatches a reactive source (getter or ref) and runs a callback on change. Supports immediate (fire once on setup), deep (track nested properties), and sync (synchronous callback) options; returns a stop function.
isReactiveisReactive(value: unknown): booleanChecks whether an object is a reactive proxy.
isReadonlyisReadonly(value: unknown): booleanChecks whether an object is a readonly reactive proxy.

reactive

import { reactive } from '@geektech/tsone';

const state = reactive({
  count: 0,
  user: { name: 'John', age: 30 },
});

effect

import { effect, reactive } from '@geektech/tsone';

const state = reactive({ count: 0 });

effect(() => {
  console.log(`Count: ${state.count}`);
});

state.count = 1;

computed

import { computed, reactive } from '@geektech/tsone';

const state = reactive({ count: 0 });
const doubleCount = computed(() => state.count * 2);

console.log(doubleCount.value);

readonly

import { reactive, readonly } from '@geektech/tsone';

const original = reactive({ count: 0 });
const readOnlyState = readonly(original);

stop

import { effect, reactive, stop } from '@geektech/tsone';

const state = reactive({ count: 0 });
const runner = effect(() => {
  console.log(`Count: ${state.count}`);
});

stop(runner);

ref

import { effect, ref } from '@geektech/tsone';

const count = ref(0);
effect(() => {
  console.log(count.value);
});

Example

import { computed, effect, reactive, readonly, ref, stop } from '@geektech/tsone';

const state = reactive({ count: 0 });
const countRef = ref(1);
const doubleCount = computed(() => state.count * 2 + countRef.value);
const runner = effect(() => {
  console.log(state.count, doubleCount.value);
});

const frozen = readonly(state);
console.log(frozen.count);
stop(runner);