Replies: 5 comments 3 replies
-
That's how React works. Fix: useEffect(() => {
const unsubscribe = subscribe(global_state, () => {
console.log(local_state);
});
return unsubscribe;
}, [local_state]); |
Beta Was this translation helpful? Give feedback.
-
@dai-shi
Unfortunately it does not work if I continuously update the local state. import { useState, useEffect } from 'react';
import { proxy, subscribe } from 'valtio'
const global_state = proxy ({foo: 0});
function App() {
const [local_state, setLocalState] = useState (0);
useEffect(() => {
const unsubscribe = subscribe(global_state, () => {
console.log(local_state);
});
return unsubscribe;
}, [local_state]);
const click = () => {
setLocalState (local_state + 1);
global_state.foo++; // triggers subscribe
};
return (
<>
<button onClick={click}>Press</button>
<div>{ local_state }</div>
</>);
}
export default App; The |
Beta Was this translation helpful? Give feedback.
-
Does this handle the edge case? useEffect(() => {
const callback = () => {
console.log(local_state);
};
const unsubscribe = subscribe(callback);
callback();
return unsubscribe;
}, [local_state]); |
Beta Was this translation helpful? Give feedback.
-
Not really, It's actually the same as useEffect(() => {
console.log(local_state);
}, [local_state]); It's not an edge case, it's just the normal case. |
Beta Was this translation helpful? Give feedback.
-
The following seems to work in this simple case
But this does not
So it does not work with nested structures, which is one point why Valtio is so attractive. |
Beta Was this translation helpful? Give feedback.
-
I have a valtio store (global state) and a local state created with
useState
. When the global state updates I want to call a function and access the current value of the local state in this function. But I only get the initial value of the local state. It does not update.Is it somehow possible to mix up both state management tools?
Beta Was this translation helpful? Give feedback.
All reactions