Getters make the component re-renders when using signals
mkhennoussi opened this issue · comments
Hi there ! Thank you for this lib, it makes a perfect combo with preact/signals.
When I use the counter example in React from the docs :
import { deepSignal } from "deepsignal";
const state = deepSignal({
count: 0,
get double() {
return state.count * 2;
},
});
function Counter() {
return (
<button onClick={() => (state.count += 1)}>
{state.$count} x 2 = {state.$double}
</button>
);
}
the component is re-rendered when I use {state.$double}
.
The same computed value doesn't make a re-render when I use it with preact directly: const double = computed(() => count.value*2)
.
If I use the same principe with deepsignal, it doesn't make a re-render :
get double() {
return computed(() => state.count * 2);
},
In the docs, you wrote : deepsignal will convert getters to computed values instead of signal instances underneath.
So I am not sure what's happening here. Is it the behaviour we should expect when using the signal state.$double
?
Thanks a lot for your help !
Your code snippet works fine for me:
https://stackblitz.com/edit/vitejs-vite-swi7hq
Screen.Capture.on.2023-12-04.at.10-31-30.mp4
Could you please try to reproduce it in a codesandbox/stackblitz/repository so I can take a look?
update: The issue is still there, caused by HMR. I don't know now where does it comes from....
Hi @luisherranz , thanks for your answers here and twitter !
Indeed, I tried on Stackblitz and CodeSandBox and it works too. So I was testing the lib with React and Typescript from the Vite Scaffolding template using pnpm create vite@latest
.
Then I found the "issue". Vite wrap the App component in React.StrictMode
:
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The strict mode which expects things such as render to be pure, so maybe this is why I got re-rendering.
As strict mode is only used in development, when I build the app, everything works great.
So this can be solve by removing the strict mode.
Thanks again for your help and your work !
Nice. I'm glad it works 🙂
Closing this now as resolved but feel free to reopen if you find any issue again.
Haha it doesn't work, I thought it was the strict mode, but it seems related to Vite HMR... but I don't know how... I'll keep you posted if I find something.
Ok! If you are able to reproduce it, reopen the issue please 🙂