I created a minimalistic app using the npx create-react-app
approach. I created a functional component
and tried if an old setValue method of a useState
hook updates the value maintained by the hook.
Therefore, I created an array listOfSetValueMethods
that contains all setValue
methods. In the myButtonClick()
method I used the first setValue
method to update the value of the hook: it does not work: react does not re-render anything: listOfSetValueMethods[0](scopeId+1);
. If I use ANY other setValue
method, it does work:
var myCounter=0;
var listOfSetValueMethods=[];
function MyComponent() {
const [currentScopeId,setValue]=useState(-1);
listOfSetValueMethods.push(setValue);
let scopeId=myCounter++;
console.log("scopeId: " + scopeId);
function myButtonClick(){
if(listOfSetValueMethods.length>0){
listOfSetValueMethods[0](scopeId+1); //does not work
//works: listOfSetValueMethods[1](scopeId+1);
console.log("setted value to:" + (scopeId+1) + ", current value in scope:" + currentScopeId);
}else{
setValue(scopeId);
}
}
return (
<div>
<b onClick={()=>{myButtonClick()}}> id: {currentScopeId}</b> <br />
</div>
);
}
What is the difference between calling listOfSetValueMethods[0](scopeId+1)
and listOfSetValueMethods[X](scopeId+1)
whereby X>0
?
Output from console:
scopeId: 0
App.js:13 scopeId: 1
App.js:19 setted value to:2, current value in scope:-1
App.js:13 scopeId: 2
App.js:13 scopeId: 3
App.js:19 setted value to:2, current value in scope:-1
App.js:13 scopeId: 4
so the current scope id remains at -1! App.js:13 scopeId: 5