Featurevisor

Framework guides

Signals

@featurevisor/signals turns what a Featurevisor instance answers into values that update themselves, and evaluate again only when something they read has changed. This page reads flags, variations and variables as values in plain JavaScript, then uses them with Preact, Lit, React and Vue.

Experimental

@featurevisor/signals is experimental, so its API may change in a minor release. The React and Vue hooks are built on it, and their own API is stable.

Install

Command
npm install @featurevisor/signals @featurevisor/sdk

The core needs nothing else. To use an adapter, install its library beside it:

ImportInstallValues are
@featurevisor/signalsSources, with read and listen
@featurevisor/signals/preact@preact/signals-corePreact signals
@featurevisor/signals/tc39signal-polyfillTC39 Signal.Computed values
@featurevisor/signals/reactreactuseSource, for a component
@featurevisor/signals/vuevueuseSource, which returns a ref

Create a reader

Create a JavaScript SDK instance, then a reader for it:

src/featurevisor.js
import { createFeaturevisor } from '@featurevisor/sdk'
import { createSignals } from '@featurevisor/signals'
const response = await fetch('https://cdn.example.com/featurevisor-all.json')
if (!response.ok) throw new Error(`HTTP ${response.status}`)
export const f = createFeaturevisor({
datafile: await response.json(),
context: {
userId: 'user-4',
country: 'nl',
},
})
export const signals = createSignals(f)

Each method of signals makes a value. A value only reads, so changes stay on the instance, through setContext, setDatafile and the sticky value setters.

Read values

read() answers now:

const checkout = signals.flag('checkout')
checkout.read() // true

user-4 is in the Netherlands, so the netherlands rule of checkout lets them in. Each call to a reader makes a new value, so keep the value you read and listen to, rather than asking the reader again.

Flags

flag(featureKey) is whether the feature is enabled:

signals.flag('checkout').read() // true

Variations

variation(featureKey) is the feature's variation, or null when it has none or is disabled:

signals.variation('pricing').read() // 'control'

Variables

variable(featureKey, variableKey) is a feature's variable, and variable(variableKey) a global variable. Each is null when there is none:

signals.variable('buyButton', 'colour').read() // '#2563eb'
signals.variable('supportEmail').read()

An object or array answer compares by value, so an answer equal to the last keeps the same object, and tells no listener:

const settings = signals.variable('checkoutSettings')
settings.read()
// { currency: 'EUR', paymentMethods: ['ideal', 'card'] }

Several flags

flags(featureKeys) gives one value per feature, in the order of the keys:

const [newCheckout, liveChat] = signals.flags(['checkout', 'liveChat'])
newCheckout.read() // true
liveChat.read() // false

everyFlag(featureKeys) is whether every feature is enabled, and someFlag(featureKeys) whether any is:

const both = signals.everyFlag(['checkout', 'liveChat'])
const either = signals.someFlag(['checkout', 'liveChat'])
both.read() // false
either.read() // true

Both evaluate in order and stop at the first feature that decides the answer, so a later feature is not evaluated, and not followed, while an earlier one decides. A key listed twice is evaluated once. With no keys, everyFlag is true and someFlag is false.

Listen for changes

listen(changed) calls changed whenever the value's answer changes, and returns a function that stops listening:

const checkout = signals.flag('checkout')
const pricing = signals.variation('pricing')
const stopCheckout = checkout.listen(() => {
console.log('checkout', checkout.read())
})
const stopPricing = pricing.listen(() => {
console.log('pricing', pricing.read())
})
f.setContext({ country: 'de' })
// checkout false

checkout read country, and in Germany user-4 is outside the everyone rule's 25%, at 89.3. pricing buckets by userId and never reads country, so the change does not evaluate it again, and its listener is not called:

countrycheckoutpricing
nltrue'control'
defalse'control'

Stop listening with the functions listen() returned:

stopCheckout()
stopPricing()

A value listens to the instance only while something listens to it, and the reader stops listening to the instance a moment after the last listener leaves. One SDK change that alters several values calls each of their listeners once, after every value has answered.

Give a value its own context

The instance is now in Germany. A value's own context is merged over the instance's, as for the SDK's own getters:

const context = { country: 'nl' }
signals.flag('checkout', context).read() // true

A context compares by value, so the same values in a new object ask nothing again.

Follow changing state

A function in place of an object is read each time the value answers, so the value follows state that changes:

const session = { country: 'nl' }
const checkout = signals.flag('checkout', () => ({
country: session.country,
}))
checkout.read() // true
session.country = 'de'
checkout.read() // false

With plain sources, the new state is seen at the next read(), and calls no listener. With an adapter, a function that reads that library's signals or refs is followed, so the value updates and tells its listeners, as Preact shows.

Scope several values

scope(context) returns a reader whose values all merge that context under their own, as FeaturevisorScope does for React hooks:

const dutch = signals.scope({ country: 'nl' })
dutch.flag('checkout').read() // true
dutch.variable('supportEmail').read()

A value's own context wins over its scopes. Scopes nest, dutch.scope(...) merging the outermost first, and a scope can take a function too.

Combine values with from

from(compute, context) makes one value from any function of a context, such as a combination of your own or another package's getter:

const summary = signals.from((context) => ({
checkout: f.isEnabled('checkout', context),
supportEmail: f.getVariable('supportEmail', context),
}))
summary.read()
// { checkout: false, supportEmail: '[email protected]' }

compute receives the value's context merged over its scopes, and the SDK's getters inside it merge that over the instance's context as usual. The value follows exactly what those evaluations read, so it asks again only when one of them could answer differently.

An equal answer keeps the previous object. A third argument, { equals }, compares answers another way, and { precise: false } asks again on every change, for a compute that reads state outside the context and the SDK.

Follow the revision

revision holds the datafile's revision, and tells its listeners when a datafile brings another:

signals.revision.read() // '1'
signals.revision.listen(() => {
console.log('revision', signals.revision.read())
})

The SDK fetches nothing, and an instance can start without a datafile or never have one, so a reader has no status of its own. Whoever sets the datafile knows when it arrives.

Choose options

createSignals(f, options) takes:

OptionDefaultWhat it does
precisetrueWith false, every value asks again on every change
freezeIn development buildsFreezes the values kept, so changing one in place throws
copyfalseGives each value its own copy, so changing it in place reaches nothing
const signals = createSignals(f, {
copy: true,
})

freeze is off when copy is set. Development builds are those where process.env.NODE_ENV is not 'production', as bundlers set it.

Use Preact signals

createSignals from @featurevisor/signals/preact gives the same reader, with Preact signals as its values:

import { computed, effect, signal } from '@preact/signals-core'
import { createSignals } from '@featurevisor/signals/preact'
const signals = createSignals(f)
const country = signal('nl')
const checkout = signals.flag('checkout', () => ({
country: country.value,
}))
const label = computed(() => (checkout.value ? 'New checkout' : 'Checkout'))
effect(() => {
console.log(label.value)
})
// New checkout
country.value = 'de'
// Checkout

Each value is a ReadonlySignal, so it works in computed, effect and Preact components alike. The context function reads country, so the value follows it. One SDK change that alters several values updates them in one batch, so an effect that reads several runs once.

Setting the context inside an effect does not make that effect depend on the values the change updates. A value listens to the instance only while something watches it.

Use TC39 signals and Lit

createSignals from @featurevisor/signals/tc39 gives Signal.Computed values from signal-polyfill, the polyfill of the TC39 signals proposal:

import { Signal } from 'signal-polyfill'
import { createSignals } from '@featurevisor/signals/tc39'
const signals = createSignals(f)
const country = new Signal.State('nl')
const checkout = signals.flag('checkout', () => ({
country: country.get(),
}))
const label = new Signal.Computed(() =>
checkout.get() ? 'New checkout' : 'Checkout',
)
label.get() // 'New checkout'
country.set('de')
label.get() // 'Checkout'

The values work inside other computed signals, with a Signal.subtle.Watcher, and with Lit's signals integration, which watches them for a component. A value listens to the instance only while a watcher watches it.

This entry is an ES module only, as the polyfill is.

Use it in React

The React hooks are built on this package, so useFlag, useFlags, useVariation, useVariable and the others already render a component again only when their own value changes. Most applications need nothing more.

For a value the hooks do not cover, such as one from from, read the reader of the nearest FeaturevisorProvider with useSignals, and the value with useSource:

src/components/CheckoutSummary.jsx
import { useMemo } from 'react'
import { useSdk, useSignals } from '@featurevisor/react'
import { useSource } from '@featurevisor/signals/react'
export function CheckoutSummary() {
const f = useSdk()
const signals = useSignals()
const summary = useMemo(
() =>
signals.from((context) => ({
checkout: f.isEnabled('checkout', context),
supportEmail: f.getVariable('supportEmail', context),
})),
[f, signals],
)
const { checkout, supportEmail } = useSource(summary)
return checkout ? <p>Questions? {supportEmail}</p> : null
}

useMemo keeps the same value between renders, since each call to a reader makes a new one. useSource renders the component again only when the value changes, from React 16.8.

Use it in Vue

The Vue composables are built on this package, so useFlag, useFlags, useVariation, useVariable and the others already update their refs only when their own value changes. Most applications need nothing more.

For a value the composables do not cover, such as one from from, read the application's reader with useSignals in setup, and the value with useSource, which returns a readonly ref:

src/components/CheckoutSummary.js
import { defineComponent, h } from 'vue'
import { useSdk, useSignals } from '@featurevisor/vue'
import { useSource } from '@featurevisor/signals/vue'
export default defineComponent({
props: {
country: { type: String, required: true },
},
setup(props) {
const f = useSdk()
const signals = useSignals()
const summary = useSource(
signals.from(
(context) => ({
checkout: f.isEnabled('checkout', context),
supportEmail: f.getVariable('supportEmail', context),
}),
() => ({ country: props.country }),
),
)
return () =>
summary.value.checkout
? h('p', `Questions? ${summary.value.supportEmail}`)
: null
},
})

The context function reads props.country, so the ref follows the prop. In a component, a ref listens once mounted and stops when unmounted.

Wrap values for another library

createReader(f, wrap) builds a reader whose values are whatever wrap makes of each source. For Svelte stores:

import { readable } from 'svelte/store'
import { createReader } from '@featurevisor/signals'
const signals = createReader(f, (source) =>
readable(source.read(), (set) => {
set(source.read())
return source.listen(() => set(source.read()))
}),
)
const checkout = signals.flag('checkout')
// a store holding true or false

A wrap should listen only while its own library watches the value, as readable does, so the instance is not listened to for nothing. In TypeScript, declare the library's type in the Wrapped interface of @featurevisor/signals under a name, and pass that name to createReader.

Details

What asks a value again

A value evaluates again only when a change touches what its last answer read:

ChangeAsks again
setContextValues that read a changed top level key
setDatafileValues that read a changed feature, global variable or segment
setStickyFeatures and setStickyVariablesValues that read a named feature or global variable

What an answer read includes its dependencies, such as chatFileUpload reading liveChat. A value that read nothing the SDK can name, such as from over a function that calls no getter, follows every change.

How answers compare

An equal answer keeps the previous value, so objects and arrays keep their identity until they change. Flags and variations compare by identity, and variables and from answers by value: arrays and plain objects item by item, and dates by time.

Modules

Modules are seen this way:

  • A module that changes answers from application state should take that state from the context. State it reads from elsewhere is not seen, so create the reader with precise: false for an application with such a module.
  • A module with beforeEvaluation, bucketKey or bucketValue may read any attribute, so the values it takes part in ask again on every context change.
  • An afterEvaluation hook that changes answers by the context is not seen.
  • A module added or removed after values have answered changes them from the next change to the context, datafile or sticky values.

Child instances

A child instance cannot say what an answer read, so its values follow every change the child reports: its own context and sticky values, and its parent's datafile. A context key the parent adds later reaches the child's evaluations at once, but its values see it only at their next change.

Errors

An evaluation that throws, such as a from whose function throws, throws from read(). A listener that throws is reported through console.error, and the other listeners are still called.

Server rendering

Reading a value on a server evaluates it without listening, so nothing attaches to an instance shared between requests. The React and Vue hooks evaluate directly while rendering on a server.

Previous
Nuxt
Next
Astro