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.

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.

Leave a Reply