signal
A lightweight, simple reactive system for your Javascript application. Zero dependencies, TypeScript fully supported.
Version
Installation
Via NPM
pnpm add @kaiverse/signal
npm i @kaiverse/signal
Via JSR
deno add @kaiverse/signal
pnpm dlx jsr add @kaiverse/signal
npx jsr add @kaiverse/signal
Via CDN
unpkg.com/@kaiverse/signal
Compatibility
Signal is a Proxy
object at its core, please check compatibility section.
Documentation
Example
🔗Signal Proxy
/** * HTML setup: * ```html * <p id="fetch-result"></p> * <button type="button" onclick="fetchNextUser()">Get next user</button> * ``` */
import {signalProxy} from '@kaiverse/signal'
const resultElement = document.getElementById('fetch-result')
const userSignal = signalProxy({userId: 123, reqCount: 0}, async (key, newValue) => { // Do something when any userSignal's prop value changes console.log(`[userSignal updated] key: ${key}, value: ${newValue}`)
if (key === 'userId') { // Do something on `userId` changes only const userId = newValue const response = await fetch(`${basePath}/user/${userId}`) const userData = await response.json() const totalReqCount = userSignal.reqCount + 1 userSignal.reqCount = totalReqCount
if (resultElement) resultElement.innerHTML = `Name: ${userData.name}<br/>Total requests: ${totalReqCount}` }})
function fetchNextUser() { userSignal.userId++}
🚦Signal utilities
If you have experience with SolidJS or ReactJS, you’ll find these utility functions very familiar.
import {createComputed, createEffect, createSignal} from '@kaiverse/signal'
const [count, setCount] = createSignal(0)
setInterval(() => { setCount((c) => c + 1) // or setCount(count() + 1)}, 1000)
createEffect(() => { // log the count signal's value to the console every 1 second console.log('count =', count())})
const doubled = createComputed(() => count() * 2)
createEffect(() => { // log the doubled signal's value to the console every 1 second console.log('[computed] doubled =', doubled())})
Framework compatibility
This package is built for vanilla JS/TS applications.
However, below are implementations to adapt with some frameworks’s reactive systems.
React Server Components/Functions
Compatible.
React
[Experimental] @kaiverse/signal-react
Docs: Hooks/signal
Playground: source code
Astro
Compatible.
You can use it in the component script section for server signals, and/or the <script>
tag for client signals.
SolidJS, VueJS
… Just use their “Signals” APIs.