0

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?

Rollie
  • 3,781
  • 2
  • 23
  • 42
  • You really need some clarity... according to your code you want to block the current thread but then how can you wait for state change – Dennis Vash Jan 17 '21 at 16:43
  • @DennisVash if you await an async function, it doesn't block the current thread; it will execute subsequent code after the awaited function (which returns a 'promise') has completed. See: https://medium.com/better-programming/understanding-async-await-in-javascript-1d81bb079b2c It's perfectly logical to stop execution of a function (either originally run from an event handler, useEffect, etc) to run indefinitely, and it won't affect rendering of DOM elements on the page, nor prevent other components changing state on which you rely. – Rollie Jan 17 '21 at 17:39
  • It is the same thread, you say you dont want to relay on render ie on state change so without it your UI will get stuck (you need another object for comparison). Sounds like https://xyproblem.info/ – Dennis Vash Jan 17 '21 at 18:03
  • If you have global state (like redux store), you can do it. Without passing another state ref you cant ahchieve it with current React API – Dennis Vash Jan 17 '21 at 18:13

2 Answers2

1

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]);
k-wasilewski
  • 2,683
  • 1
  • 5
  • 15
0

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);
Vipul Kumar
  • 415
  • 2
  • 10