Similar to:
- How to use `setState` callback on react hooks but I am trying to do this with functional component specifically and I am not trying to replicate the exact same scenario.
- React hooks: accessing up-to-date state from within a callback but I am not passing the state from the callback
So say I have a notify()
method that I want to be fired AFTER the states have changed, not during state change. Also after I click
.
something like
const handleClick = useCallback(()=>{
const [state,setState] = useState("bar");
...
setState("foo", ()=> {
... at this point `state` should be "foo" ...;
notify("yo we're set. but I am not passing the current state to you");
})
});
...
a component that is child of the context
const { state } = useSomeContext();
subscribe(()=>{
console.log("I want ", state, " to be the updated value, but I get the existing value);
});
useStateRef
lets the callback know but the ones listening when they query the value that is in the state may not get the updated value.useStateCallback
does not solve the problem for me either because it's the callback that has the value.
The workaround I sort of ended up with (still testing it) is to utilize a useRef
to the value somewhat like useStateRef
and do stateRef.current
instead of just state