Search code examples
javascriptreactjssolid-js

how to implement the `createSignal` for react?


createSignal returns the state's getter is more helpful for many cases in react dev.

such as this bug component (useState closure problem):

function AutoCounter() {
    const [c, set] = useState(0)
    useEffect(() => {
        setInterval(() => set(c + 1), 500);
    }, [])
    return <div>counter: {c}</div>
}

Solution

  • React and Solid have different runtimes and they have different execution models. As you might expect, implementation of a signal in React is not trivial, because a signal is more than a wrapper function that returns a pair of getter and setter functions.

    React employs component-level re-rendering, which gives a sense of reactivity, but it is not truly reactive. It has a complex rendering mechanism, which makes it very difficult to retrofit Solid's like signal mechanism, regardless of whether you need signals in React or not.

    Reactivity is a quite complex topic to cover in a SO answer because it is more of a programming paradigm or a programming model than a specific implementation that requires a specific set of features.

    There are different libraries that implement signal or signal like constructs while using React's syntax and execution model. Preact is the most well-known one, which you can check out https://github.com/preactjs/signals