@dmytromykhailiuk/reactive-react
v1.1.0
Published
Simple and Powerful Signal implementation for React
Downloads
3
Readme
Reactive
Simple and Powerful Signal implementation for React
*Solutition uses reactive package under the hood
Installation
npm i @dmytromykhailiuk/reactive-react
Basic example of usage
import { useSignal, useComputedSignal, useSignalEffect, useDebouncedSignalEffect } from '@dmytromykhailiuk/reactive-react';
const a = useSignal(1);
const b = useSignal(2);
const c = useComputedSignal(() => a.value + b.value);
console.log('ComputedSignal', c.value);
// ComputedSignal 3
a.value = a.value + 1;
b.value = b.value + 2;
console.log('ComputedSignal', c.value);
// ComputedSignal 6
const effect = useSignalEffect(() => console.log('SignalEffect', c.value));
// SignalEffect 6
a.value = a.value + 1;
// SignalEffect 7
a.value = a.value + 1;
// SignalEffect 8
b.value = b.value + 2;
// SignalEffect 10
b.value = b.value;
effect.destroy();
const debouncedEffect = new useDebouncedSignalEffect(() => console.log('DebouncedSignalEffect', c.value));
// DebouncedSignalEffect 10
a.value = a.value + 1;
a.value = a.value + 1;
b.value = b.value + 2;
// DebouncedSignalEffect 14
IMPORTANT: changing the signal value dosn't trigger component update
For component update we need to use useReactive or useComponentUpdateWithSignal hooks
Example of useReactive usage
import { useCallback } from 'react';
import { useSignal, useComputedSignal, useReactive } from '@dmytromykhailiuk/reactive-react';
const ExampleComponent = () => {
const signal = useReactive(useSignal(0)); // can pass signal or computed
return <>
<div>signal value - {signal.value}</div>
<button click={() => signal.update(value => value + 1)}>increase signal value</button>
</>
}
Example of useComponentUpdateWithSignal usage
import { useCallback } from 'react';
import { useSignal, useComputedSignal, useComponentUpdateWithSignal } from '@dmytromykhailiuk/reactive-react';
const ExampleComponent = () => {
const firstSignal = useSignal(0);
const secontSignal = useSignal(0);
const computedSignal = useComputedSignal(() => firstSignal.value + secontSignal.value);
useComponentUpdateWithSignal(computedSignal); // We can pass multiple signals
const inscreaseSignalValue = useCallback((signal) => {
signal.value = signal.value + 1;
}, []);
const inscreaseFirstSignalValue = useMemo(() => inscreaseSignalValue.bind(null, firstSignal), []);
const inscreaseSecondSignalValue = useMemo(() => inscreaseSignalValue.bind(null, secontSignal), []);
return <>
<div>computedSignal - {computedSignal.value} </div>
<button click={inscreaseFirstSignalValue}>increase first signal</button>
<button click={inscreaseSecondSignalValue}>increase second signal</button>
</>
}