Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In a Chrome Extension, using React, how can you replace an old listener that references old state?

I have an issue in a component where I’m simply using chrome.runtime.onMessage.addListener, where my listener is dependent on the current component’s state.


The problem is that when the state of the component updates, this listener is old, and is referencing an old state value. I have seen people use a ref (so they can access .current at invocation to get the fresh value) but I find it hard to believe this is the real answer, since my state will need to be duplicated as refs.

I think the real solution would be useEffect to removeListener(oldListener) and addListener(newListener) but this has the problem where I now need to keep track of my old listener.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I feel like I’m missing something very obvious here; how can I maintain a listener that references current state?

>Solution :

To keep track of the listener and update it when the state changes. One way to do this is to use the useEffect hook to add and remove the listener whenever the state changes. You can use the useRef hook to store the listener and use it in the useEffect callback. This way, you can access the current listener whenever the state changes.

If you could show the code it would be easier to answer, greetings.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading