Answer the question
In order to leave comments, you need to log in
How to update a react component after a change in an object?
Good afternoon, I can’t figure out how to update the react component after changing one of the properties of the object
factorModel
export default function SensorFactorEditComponent ({ factor, id, fullWidth, showMessage }) {
const factorModel = new FactorModel();
const [isChanged, setIsChanged] = useState(false);
useEffect(() => {
factorModel.on('change:factor', () => {
//Обновляю состояние компонента после изменения свойства объекта что бы компонент обновился
setIsChanged(!isChanged);
})
});
const updatedFactor = () => {
//После изменения состояния компонент обновляется но всё время выдаёт старое значение
return <div>{factorModel.getFactor()}</div>;
}
return (
<>
<Form model={factorModel}>
<Input
type='number'
name='factor'
value={factorModel.getFactor()}
fullWidth={fullWidth}
/>
</Form>
{updatedFactor()}
</>
);
}
Answer the question
In order to leave comments, you need to log in
First, you will create a new instance of the FactorModel() object every render. Those. every render iteration you have a newly initialized object.
To avoid this, you must either memoize this instance (the useMemo hook), or instantiate the object outside the component (if possible).
Secondly, the effect is also called every render, and a new function is subscribed to the event every time (memory leaks). To avoid this, you need to specify the second parameter in useEffect: useEffect(..., []) - this effect will be performed only when the component is mounted.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question