react-konva icon indicating copy to clipboard operation
react-konva copied to clipboard

useEffect blocks first draw

Open Belisarith opened this issue 6 years ago • 1 comments

When I have an effect, that does a lot of stuff, the first render is blocked till the effect is finished. In my real application I use the effect in order to prepare complex svgs by passing them to canvg. But this is not the problem, I think.

For example, if I have this simple effect: useEffect(() => { console.log("start effect"); for (let i = 0; i < 5e9; i++) {} console.log("end effect"); }); and this really simple drawing:

return ( <Stage height={canvasHeight} width={canvasWidth} scaleX={1} scaleY={1}> <Layer> {console.log("Rendering")} <Rect x={100} y={200} width={500} height={500} stroke="magenta"></Rect> </Layer> </Stage> );

I get the following output on my console: Rendering start effect end effect Rendering start effect end effect

However, although rendering is written to the console (the console log is in between the JSX react-konva elements) the rectangle only shows after the effect ended, i.e. after end effect is written to console.

Am I doing something wrong? Is this intentional behavior? Are there best practices to render the canvas for the first time before the effect is finished?

Belisarith avatar Feb 23 '20 12:02 Belisarith

react-konva doesn't render into the canvas immediately. For performance reasons, it is drawing as soon as possible in async way.

Probably useEffect is running BEFORE drawing into the canvas. To resolve the issue you can:

Get access to stage or layer directly with ref and call draw() method manually before running a long task.

You may need to run a long task is async way too, so the browser has time to update the screen. Something like this:

useEffect(() => {
   const timeout = requestAnimationFrame(longTaskFunction);
   return () => cancelAnimationFrame(timeout);
});

lavrton avatar Feb 24 '20 13:02 lavrton