I have one function component in React, and I am also using the KonvaJS npm library. While the function component re-renders it, it increases the memory footprint.
My code
import React, { useState, useEffect, useSelector} from "react";
import { Stage as stageKonva } from "konva/lib/Stage";
import { Line as LineKonva } from "konva/lib/shapes/Line";
import { Animation as AnimationKonva } from "konva/lib/Animation";
import { Layer as LayerKonva } from "konva/lib/Layer";
import { Image as ImageKonva } from "konva/lib/shapes/Image";
export const Abc = (data)=>{
const { device } = useSelector((state) => ({ device: state.device }));
useEffect(() => {
gameStart();
},[device])
async function gameStart (){
var stage = new stageKonva({ container: "gamePanel", width: 300, height: 300});
var layer = new LayerKonva(), oldRow = null; stage.add(layer);
var imageObj1 = new Image();
imageObj1.onload = function () {
let square = new ImageKonva({ x: 0, y: 0, height: 40, width: 20, image: imageObj1 });
------------------------------
---------Some code here-------
------------------------------
}
imageObj1.src = data.image;
}
return(<div id="gamePanel"></div>);
}
I want to know why the memory footprint is increasing while re-rendering. How to stop that?
You should do a deeper memory profiling and see what is in the memory.
From your code, it is hard to say when you run the effect and how many times.
useEffect(() => {
gameStart();
},[device])
Probably it is called many times, so it creates many Konva nodes instances in the memory. You can do clean in the effect:
function gameStart (){
var stage = new stageKonva({ container: "gamePanel", width: 300, height: 300});
// some other game code
return stage;
}
useEffect(() => {
const stage = gameStart();
return () => {
stage.destoy();
}
},[device])
Destroying just the stage may not be enough. You may need to check animations and other intances.