DEV Community

Discussion on: React vs Signals: 10 Years Later

Collapse
 
inwerpsel profile image
Pieter Vincent • Edited

Fun fact: take a hook that uses a subscription (e.g. by directly using useSyncExternalStore), and use it as a component...

You now have a signal, written in React, with 0 external dependencies.

function useFoo() {
  return useSyncExternalStore( /* ... */);
}

function Normal() {
  const foo = useFoo();

  return foo === 'bar' ? BarComponent : OtherComponent;
}

// Temporary uppercase name to make JSX work.
const FooSignal = useFoo;
// Yes, this only needs to happen once for the whole app.
const $foo = <FooSignal />;

function WithSignals() {
  return <div>
    // ...
    <h2>{$foo}</h2>
    <p> Some other stuff that last rendered at {performance.now()}</p>
  </div>;
}
Enter fullscreen mode Exit fullscreen mode

This works with any argumentless hook that properly manages global state.

working codesandbox