1

Signals In React | Catching up with the latest trends

 8 months ago
source link: https://dev.to/davidkohen/signals-in-react-294b
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Cover image for Signals In React | Catching up with the latest trends
David Kohen

Posted on Dec 23

6 1 1 2 1

Signals In React | Catching up with the latest trends

It's intriguing to see that almost every JavaScript client framework has now implemented signals.

A pattern that was once deemed old and primitive has become the flagship feature of so many frameworks.

But it seems that the React team is still against the idea as they:
"don’t think it’s a great way to write UI code" as mentioned here:

But this doesn't mean all hope is lost.
After exploring the @preact/signals-react package I've found that there are some incredible possibilities when it comes to using signals in React.

All of the drawbacks of using React state are gone!!

No more prop drilling or prev-callbacks and it even allows direct mutation of the signal value.

Unfortunately, though, that library doesn't integrate well with React's state-based ecosystem and even somehow managed to break React's internal rendering queues("Which I discovered a bit too late").

So I thought that I might have a go at building a signal-based state manager for React.

So after tons of experimentation and testing, I think it is finally ready to be shared.

Here is a very basic example:

import { createSignal } from 'react-use-signals';

export const counterSignal = createSignal(0);

export const handleIncrement = () => {
  counterSignal.value += 1;
};

const Counter = () => {
  const count = counterSignal.useStateAdapter();

  return (
    <div>
      <p>Count: {count.value}</p>
      <button onClick={handleIncrement}>Increment</button>
    </div>
  );
};

And there are plenty more where that came from!!

There are more examples of how to use signals as a store, optimized rendering, selectors, and more.

Feel free to check it out on NPM:
https://www.npmjs.com/package/react-use-signals

And if you're looking for a detailed article on how they work:
https://medium.com/@personal.david.kohen/the-quest-for-signals-in-react-usestate-on-steroids-71eb9fc87c14

Any suggestions or feedback would be highly appreciated.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK