Is there a way to await changes in state? (not setState)

666 Views Asked by At

I want to await for changes in shared state and act on those, so:

function Foo() {
  const [bar, setBar] = useContext(myContext)

  const someHandler = async () => {      
    doSomething()
    while(true) {
      await stateDidChange(bar)
      doSomething()
    }
  }

  // apply someHandler to a button, etc
}

(yes, I know I can achieve something similar by removing the while loop and waiting for re-render - humor me :))

Is there a function like stateDidChange(someRandomState) as used above, or can one be generically written?

2

There are 2 best solutions below

1
k-wasilewski On

It's called componentDidReceiveProps(prevProps, prevState) or just a useEffect hook with the prop/state value you want to track as a dependency:

useEffect(() => {

}, [bar]);
0
Vipul Kumar On

You may like to use a callback pattern.

const callbackFunction = () =>  console.log("Some code");

const stateDidChange = (option = {}) => {
        if(option.cb){
                option.cb();
        }
};

const option = {};
option.cb = callbackFunction;

stateDidChange(option);