I was working on my React investment calculator project (view project), and I was experiencing some lag time when it came to the project loading for large numbers. I was calculating what the investment had grown to by a certain age. The default age input was 65, but I noticed by accident that by typing in an extra number (e.g. “655”), the program took around 5 seconds to calculate the total. I thought this was strange since I figured it should only be running around 600 calculations, and that shouldn’t take anywhere near 5 seconds.
I realized that I was doing a couple things wrong in my program. For one, I had multiple
setState() functions inside of a
useEffect(). I didn’t need these there, since they did not need to run every when the parent component updated. It turned out that I didn’t need to use state for many of these variables at all, since several of them were calculated based on input variables. That is to say, I didn’t need to have an input variable getting set from state, and then have another state variable getting set from that initial input state. It was enough to just declare a normal variable in the component and let that run when the component updated.
I fixed this, but the program was still running slow. I was able to figure out that the other main problem was that a bar chart that I had set up using an NPM library was rendering slowly when the ending age was too high, probably because of the complexity of the SVG. I decided to solve this using a restriction on how high the final age could be.
I wanted to share these thoughts that I went through while working on this project. I am still working on optimizing and finishing it up, but it has been lots of fun so far!