signals-react-safe v1.1.2
signals-react-safe
Signals is a state management library from the Preact team.
The team provides a react compatibility library (signals-react)[@preact/signals-react], but it comes with a very large downside: It alters React's internals. This is a big no-no for mainting compatibility with future versions of React, creating risk for your project. It also breaks compatibility with Next.js, which is a pretty good and popular React framework.
This library still lets you get the biggest benefit of Signals. When you render a signal directly within your JSX/TSX it creates a text node that updates when the signal updates, skipping the re-render of the component you render it within.
Install
npm install signals-react-safe
Usage Example
mySignals.ts
import { signal } from 'signals-react-safe';
export counter = signal(0);
Counter.tsx
(this component does NOT re-render when the signal updates, which is more performant)
import { counter } from "./mySignals";
export function Counter() {
return (
<div>
<div>Current Count: {counter}</div>
<button onClick={() => counter.value++}>Add One</button>
</div>
);
}
MixedCounter.tsx
(this component does re-render when the signal updates, which allows the value to be combined with non-signal values)
import { useState } from "react";
import { counter } from "./mySignals";
export function MixedCounter() {
const counterValue = useSignalValue(counter);
const [myCounter, setMyCounter] = useState(0);
return (
<div>
<div>Summed: {counterValue + myCounter}</div>
<button onClick={() => counter.value++}>Add One to signal counter</button>
<button onClick={() => setMyCounter(myCounter + 1)}>
Add One to useState counter
</button>
</div>
);
}
API
This library provides a bunch of exported function:
- Re-exports from the core Signals library:
signal
,computed
,effect
. - Copy/pasted hooks from @preact/signals-react:
useSignal
,useComputed
,useSignalEffect
. - New hooks unique to this library:
useSignalValue
,useSignalAndValue
,useComputedValue
.
Author
Created by Jon Abrams (2023)
Attributions
Contains code from Preact Signals
Idea inspired by satoshi-cyber's suggestion.
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
6 months ago
6 months ago
6 months ago
6 months ago