Share Store State with Signal Pattern
npm install reactjs-signal
import React from 'react';
import { useSignal } from 'reactjs-signal';
const App = () => {
const [state, setState] = useSignal({ count: 0 });
return (
<div>
<h1>{state.count}</h1>
<button onClick={() => setState({ count: state.count + 1 })}>Increment</button>
</div>
);
};
Creates a writable Alien Signal.
const countSignal = createSignal(0);
countSignal(10); // sets the value to 10
initialValue
(T
): The initial value of the signal.
IWritableSignal<T>
: The created Alien Signal.
Creates a computed Alien Signal based on a getter function.
const countSignal = createSignal(1);
const doubleSignal = createComputed(() => countSignal() * 2);
fn
(() => T
): A getter function returning a computed value.
ISignal<T>
: The created computed signal.
React hook returning [value, setValue]
for a given Alien Signal. Uses useSyncExternalStore
for concurrency-safe re-renders.
const countSignal = createSignal(0);
function Counter() {
const [count, setCount] = useSignal(countSignal);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
alienSignal
(IWritableSignal<T>
): The signal to read/write.
[T, (val: T | ((oldVal: T) => T)) => void]
: A tuple[currentValue, setValue]
.
React hook returning only the current value of an Alien Signal (or computed). No setter is provided.
const countSignal = createSignal(0);
const doubleSignal = createComputed(() => countSignal() * 2);
function Display() {
const count = useSignalValue(countSignal);
const double = useSignalValue(doubleSignal);
return <div>{count}, {double}</div>;
}
alienSignal
(IWritableSignal<T>
): The signal to read.
T
: The current value.
React hook returning only a setter function for an Alien Signal. No current value is provided, similar to Jotai's useSetAtom
.
const countSignal = createSignal(0);
function Incrementor() {
const setCount = useSetSignal(countSignal);
return <button onClick={() => setCount((c) => c + 1)}>+1</button>;
}
alienSignal
(IWritableSignal<T>
): The signal to write.
(val: T | ((oldVal: T) => T)) => void
: A setter function.
React hook for running a side effect whenever Alien Signals' dependencies used in fn
change. The effect is cleaned up on component unmount.
function Logger() {
useSignalEffect(() => {
console.log('Signal changed:', someSignal());
});
return null;
}
fn
(() => void
): The effect function to run.
React hook to initialize a signal with a value when hydrating from server.
const countSignal = createSignal(0);
useHydrateSignal(countSignal, 10);
alienSignal
: The signal to hydrate.value
: initial value
EffectScope
: The created effect scope.
React Alien Signals is a TypeScript library that provides hooks built on top of Alien Signals.