DEV Community

vive
vive

Posted on

Understanding Expensive Calculations in React for Beginners

Hey there 👋

In React development, many factors influence the overall performance of an application. One key factor is the efficiency of calculations. But how can we determine if a calculation is expensive? And why is it so important to know?

React developers, especially beginners, often overuse such hooks like useState and useEffect. Understanding whether a calculation is expensive can help you decide if state or effects are necessary, or if it is acceptable to re-calculate something on every render.

Let's get straight to the point with key factors to consider. By the end, you’ll have a clear checklist to help you identify costly calculations in your React projects.

Theoretical analysis

Time complexity

  1. Constant time O(1)
    Operations like simple arithmetic or accessing a fixed element are considered cheap calculations.

  2. Linear time O(n)
    Iterating over a list once. The cost depends on the size of the list.

  3. Quadratic time O(n^2)
    Nested loops where each element is compared or processed multiple times. These are generally considered as expensive calculations.

  4. Exponential time O(2^n)
    Processes like deep recursion or brute-force searching. These are highly expensive calculations

Data size

  1. For small lists (< 100) - Calculations with O(n) are usually fine and considered cheap.
  2. For large lists (>1000) - Even calculations O(n) can become expensive.

Practical test

Browser performance monitoring

Console timing

console.time('name-of-the-process')
process code (calculation)
console.timeEnd('name-of-the-process')
Enter fullscreen mode Exit fullscreen mode

If the time is less than 1-2 ms - the calculation is considered as inexpensive.

Performance tab
The browser's performance tab provides a lot of useful information. While I'm not going to describe it in this article (it deserves its own article), I recommend to learn more about it.

Frequency of calculation

Even if a calculation isn't expensive, if it's being performed extremely frequently, it can still contribute to performance issue.

User experience and performance bottlenecks

The user experience is the best indicator of performance. Ask yourself: Is UI sluggish and unresponsive or smooth and responsive?
If your app has issues in these areas, it might be required to optimize expensive calculations.

Conclusions

I hope the topic became clearer for you. This article is a start to further exploration and learning about React and performance. Consider learning about React's optimization techniques like useMemo and React.memo, diving into browser performance tools, or strengthening your understanding of algorithms and data structures.

Top comments (0)