You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionApp(){// We will set the state from one listener and read it from another listenerconst[count,setCount]=useState(0);// Set up event listenersuseEffect(()=>{// Handle the "event" eventconstunlisten=listen("event",(event)=>{setCount(event.payload);});// Handle the "event-2" eventconstunlisten2=listen("event-2",(event)=>{// !! This is a race bug; `count` here will NOT always be the latest value from the callback abovefoo(count);});return()=> ...;// unlistening is omitted because it's not relevant here},[])}
If you emit the events in succession like this: event and then event-2, then the value of count in the second callback will not be the latest value as set by the first callback, because the second callback can run before App() is called again with the new state.
One possible solution is to use useRef instead and directly write/read from the ref. However, this isn't ideal if you need to render count, since automatic rerendering only happens with useState.
Another idea you is to use useRef in conjunction with useState, updating the ref value in a useEffect by depending on the state like so:
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Currently, the following is a race bug:
If you emit the events in succession like this:
event
and thenevent-2
, then the value ofcount
in the second callback will not be the latest value as set by the first callback, because the second callback can run beforeApp()
is called again with the new state.One possible solution is to use
useRef
instead and directly write/read from the ref. However, this isn't ideal if you need to rendercount
, since automatic rerendering only happens withuseState
.Another idea you is to use
useRef
in conjunction withuseState
, updating the ref value in auseEffect
by depending on the state like so:But this is not a solution, because the
useEffect
callback happens even later in the rendering lifecycle.So, what's an idiomatic way to go about this?
Beta Was this translation helpful? Give feedback.
All reactions