I have an object constructor which have method to modify a value. and I created a new instance of that object in a react component and rendering that counter in a child component. when I call method from child it getting updated in object but the newly update value is not re-rendering. I tried useEffect to listen a change in props but it getting called when value update. but when I change a state in child component the updated values are showing. What is the problem?
function Core() {
this.counter = 0;
}
Core.prototype.handleCounter = function(options) {
this.counter = this.counter + 1;
console.log(this.counter);
};
export default function App() {
let core = new Core();
return (
<div className="App">
<Status counter={core.counter} core={core} />
</div>
);
}
App.js
import React, { useEffect } from "react";
import "./styles.css";
export default function Status({ core, counter }) {
const [localState, setLocal] = React.useState(false);
function handleButton() {
core.handleCounter();
console.log(core.counter);
}
return (
<div>
<span> counter is {core.counter}</span>
<button onClick={() => handleButton()}>update object</button>
<button
onClick={() => {
setLocal(!localState);
}}
>
toggle localState
</button>
</div>
);
}
status.js
here is a code-sandbox url :https://codesandbox.io/s/quizzical-bash-qh8mn