2

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?

1
  • Why you want to use preact/signals-react package you can achieve same result using setState hook ? Commented Feb 28, 2024 at 18:41

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.