Home > Software design >  Get notified when ref.current changes in React
Get notified when ref.current changes in React

Time:07-22

Is there a way to get notified when ref.current changes in React ? Like the code below.

const ref = useRef(0);

// pseudo code
ref.addCallback((newValue)=> {
  // notified
});

ref.current = 1; // triggers the notification.

CodePudding user response:

You can make use of the useCallback hook like so:

const onChange = useCallback(value => {
   if(value) {
      // do whatever you want
   }
}, []);

And pass the function to the ref ref prop:

<div ref={onChange}></div>

Note that this does not trigger rerendes yet. You would need to set value to a state.

CodePudding user response:

You can use a library like Observable Slim

Here is an example of how you would use it:

ObservableSlim.create(ref.current, true, function(changes) {
    console.log(JSON.stringify(changes));
});
  • Related