Preact JavaScript framework gets Signals: a better way to manage state?

Preact JavaScript framework gets Signals: a better way to manage state?

The Preact team has introduced a new feature called Signals, claiming that it is “a better way to manage state.”

The idea of signals is to optimize the processing that takes place when the data that defines the state of an application changes. In an example from the introductory post, converting code from using React hooks – an older method for updating state – performs four to five times faster.

“The signals version vastly outperforms the update mechanism of any traditional Virtual DOM based framework. In some apps we’ve tested, signals are so much faster that it becomes difficult to find them in the flamegraph at all,” wrote the Preact developers.

Signals performance versus React hooks

The idea of Signals is that where there is a tree of components, a signal object which contains a value only triggers an update in components that need it. “Instead of passing a value directly through the component tree, we pass a signal object containing the value (similar to a ref). When a signal’s value changes, the signal itself stays the same. As a result, signals can be updated without re-rendering the components they’ve been passed through, since components see the signal and not its value,” the team explained.

From a coding perspective, signals are easy to use. The code for the component just needs to access the value of a signal object. When that value changes, the component automatically updates. “Accessing a signal’s value in a component automatically subscribes to updates, without the need for selectors or hooks,” said the developers.

Coding with signals: straightforward at a high level

That said, some developers have expressed concern over the way signals are implemented. “It seems like an unsafe approach to React 18+ by monkey-patching React internals state transitions, as well as mutating refs during rendering which can break during concurrent updates,” said one person on Hacker News. Another said though, “this actually looks great to use! I’m all for having more solutions for the global state problem.”

Preact is an alternative to React designed to be small and lightweight. It aims to be mostly but not completely compatible with the React API. One difference is that unlike React, Preact relies on the “browser’s standard addEventListener” for event handlers, rather than using a library that supports older browsers at the expense of size and performance. Preact is also “built with ES modules in mind from the beginning.” Switching from React to Preact is an easy win for developers in search of faster performance, in cases where the extra features of React are not required.