Kerstin Bachmann
unread,Oct 5, 2023, 2:48:24 PM10/5/23Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Chromium Extensions, Simeon Vincent, Chromium Extensions, Kerstin Bachmann
Hello Simeon,
thank you for your answer and your time.
I don't think useState is the problem, here. The Problem is already in the Code Block:
chrome.runtime.onConnect.addListener((port) => {
port.onMessage.addListener(newInfo => {
console.log(stateA); // pos B
setStateA([...stateA, newInfo]);
})
});
Lets call this Block X.
For example can console.log at pos B also not see an updated stateA (by the way, also other states which do completly different things will stay the initialized state inside Block X). So it seems that Block X can see variables from outside, but only the initiated states, not updated ones. So you can not update a state inside Block X, where you need the previous state as a basis for.
The reason why useEffect is sometime used for external sources is because of side effects. For example, if you fetch information from an API and put it in a state. The can produce an infinity loop of re-rendering:
fetch -> state -> re-render -> fetch -> state -> ...
Here we wouldn't have such a problem. Because Block X would only be called if a newInfo is
received.
The other problem with using useEffect here is we need a dependecy. The dependency should be a state inside the component or a prop which will be passed from a perent to this component. Here the incomming newInfo should be the trigger. What we can do is the following: put this new Info in an additional state, and this state is the trigger for the useEffect to enrich the array.
This is more or less the solution I explained in the second post.
Conclusion:
- I think the rules corresponding to react state inside Block X are not intuitive. And with my current knowledge, I can't see the reason behind this.
- To bypass this situation we have to create an unnecessary additional state and with this unnecessary re-renderings.
Because of this, the question is still to find a more eloquent way to handle this situation.
Best wishes