React state has no type of its own. I gave it one, and it compiles away
In Vue, Solid, and Angular, state has a type of its own: Ref<T> , Accessor<T> , Signal<T> . In React, the count from useState is just a number . Nothing in the type tells you: that it re-renders the component, that it belongs in the dependency array of an effect, that a closure may be holding an old copy of it. Those questions are left to you and to lint rules. I wanted the type to answer them,…
React doesn't have a built-in state type with its own properties. However, by creating a custom React preprocessor, one can add such functionality. This preprocessor, named "react-preprocessor," is still in an experimental phase, and the API is subject to change. The developer shared this progress to gather feedback.
The preprocessor introduces two main concepts: Reactive T and Derived T. Reactive T represents reactive state, while Derived T is computed from Reactive T.
In the example provided, a Todo component is created using this preprocessor. It defines a Todo interface with id, title, and done properties. The Todos component uses the reactive.new function to create a reactive array of Todo objects. A derived number called left is computed from the todos array using the derive function, which filters the list to include only non-done todos and calculates their length.
The component also uses a useEffect hook to update the document title based on the owner and the left value. Each todo item is rendered as a list item (li), with onClick event handling and an update function to toggle the done state. The title of each todo is derived using the todo.title property.
The preprocessor handles several tasks at build time, including generating the dependency array for the effect, creating nested immutable updates, finding items by key instead of index, and ensuring updates are pure functions. Additionally, it provides rules such as not allowing direct access to the value of Reactive T, requiring updates to be pure functions, and using lenses for nested state updates.
This preprocessor does not introduce a runtime library; Reactive T only exists at compile time, and the output only imports React. It is not a performance tool but relies on the React Compiler for memoization. The source code remains valid TypeScript, allowing editors, type checkers, and formatters to function as usual.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.