-
Loving the simplicity of valtio, however I am trying to figure out how to achieve the following behaviour: Please refer to CodeSandbox here: https://codesandbox.io/s/modern-rgb-x9pef
Desired behaviour: counter resets when hiding then showing component (like the 'React useState test' counter). I'm guessing this is probably something very basic or I'm using the wrong pattern. Any help would be appreciated! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 12 replies
-
In this case, I would suggest to reset proxy state explicitly.
Alternatively, you could store the proxy state in useRef to work with react component lifecycle. export const ValtioLocalStateTest = () => {
const state = useRef(proxy({ count: 0, userName: "Default userName" })).current
const snap = useSnapshot(state)
return (
<div>
<h3>Valtio local state test</h3>
<div>Counter: {snap.count}</div>
<div>
<button onClick={() => ++state.count}>Counter +1</button>
</div>
<div>Username: {snap.userName}</div>
<div>
<input value={snap.userName} onChange={(e) => { state.userName = e.target.value }} />
</div>
</div>
)
} But this doesn't make much sense. useImmer would be a better fit for local state. |
Beta Was this translation helpful? Give feedback.
-
I read the wiki
|
Beta Was this translation helpful? Give feedback.
-
Hi. I have this scenario
It feels weird that it doesn't work like that and valtio compares them by reference even the substate was modified and some cloning need to be used.
Why valtio cannot figure out that substate had been modified and need to be re initialized even if it the same object ref? |
Beta Was this translation helpful? Give feedback.
In this case, I would suggest to reset proxy state explicitly.
https://codesandbox.io/s/currying-cherry-yh5ip
Alternatively, you could store the proxy state in useRef to work with react component lifecycle.