1.1.2 • Published 6 months ago

signals-react-safe v1.1.2

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

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.

Live editable demo

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.

2.0.0-beta.2

5 months ago

2.0.0-beta.1

5 months ago

2.0.0-beta.6

5 months ago

2.0.0-beta.5

5 months ago

2.0.0-beta.4

5 months ago

2.0.0-beta.3

5 months ago

1.1.2

6 months ago

1.1.1

6 months ago

1.1.0

6 months ago

1.0.0

6 months ago