reactjspreactpreact-signal

React component does not update using preact/signals-react


I am using @preact/signals-react version 2.0.0, implementing a simple counter app:

import { signal } from "@preact/signals-react";

const counter = signal(0);

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <p>
          Count: {counter.value}
        </p>
        <button onClick={() => {
          counter.value += 1;
        }}>
          Click me
        </button>
      </header>
    </div>
  );
}

export default App;

enter image description here

The problem is that, the counter does not update when button is clicked. However, if I rewrite the counter display:

<p>
  Count: {counter}
</p>

The component re-rendered and the counter value display as expected.

I was thinking counter.value is the right approach to access the signal value. What is the reason behind of this?


Solution

  • Because you haven't followed the instructions: https://github.com/preactjs/signals/tree/main/packages/react#react-integration

    You need to use the Babel plugin or the useSignals() hook.

    I was thinking counter.value is the right approach to access the signal value.

    Again, the docs are your friend here: https://github.com/preactjs/signals/tree/main/packages/react#rendering-optimizations

    .value does indeed access the signal value, but if you use counter by itself, this can bypass rerenders.