Code Optimization Techniques: Algorithms, React and Network

Milliseconds matter. These are the three areas I focus on to keep applications fast: the algorithms underneath, how often React re-renders, and how much data travels over the network.

By Wasif Rehman · · Web development

In short

  • Start with the algorithm: moving from O(n²) to O(n log n) can drastically cut processing time on large datasets.
  • Use React.memo, useMemo and useCallback so components only re-render when they need to.
  • Shrink payloads with compression, code splitting and lazy loading.
  • Efficient caching makes an application feel faster to respond.

Why code speed optimization matters

In a fast-paced digital world, milliseconds matter. Speed and efficiency are a necessity, not a nice extra. I focus on three core areas, from the lowest level up:

Three areas of code speed optimization
AreaWhat to doWhat it improves
AlgorithmsChoose the right algorithm, for example O(n log n) instead of O(n²)Processing time on large datasets
React renderingUse React.memo, useMemo and useCallbackFewer unnecessary re-renders on the front end
NetworkCompress assets, split code, lazy load and cachePayload size and perceived response speed

Algorithmic efficiency: from O(n²) to O(n log n)

The foundation of optimization is choosing the right algorithm. Moving from O(n²) to O(n log n) can drastically reduce processing time for large datasets.

A simple example is checking a list for duplicates. Comparing every item with every other item is O(n²). Sorting first and then comparing neighbors is O(n log n):

// O(n²): compares every pair of numbers
function hasDuplicateSlow(numbers) {
  for (let i = 0; i < numbers.length; i++) {
    for (let j = i + 1; j < numbers.length; j++) {
      if (numbers[i] === numbers[j]) return true;
    }
  }
  return false;
}

// O(n log n): sort once, then compare neighbors
function hasDuplicateFast(numbers) {
  const sorted = [...numbers].sort((a, b) => a - b);
  for (let i = 1; i < sorted.length; i++) {
    if (sorted[i] === sorted[i - 1]) return true;
  }
  return false;
}

How to prevent unnecessary re-renders in React

On the front end, preventing unnecessary re-renders is key. Components should only update when they really need to. React gives you three tools for this:

React memoization tools
ToolWhat it memoizesUse it for
React.memoA componentSkipping a re-render when its props have not changed
useMemoA computed valueAvoiding an expensive recalculation on every render
useCallbackA functionKeeping the same function between renders, so memoized children do not re-render
import { memo, useCallback, useMemo, useState } from 'react';

// Re-renders only when its props change
const ProductRow = memo(function ProductRow({ product, onSelect }) {
  return <li onClick={() => onSelect(product.id)}>{product.name}</li>;
});

function ProductList({ products, query }) {
  const [selectedId, setSelectedId] = useState(null);

  // Recalculated only when products or query change
  const visible = useMemo(
    () => products.filter((p) => p.name.includes(query)),
    [products, query]
  );

  // Same function on every render, so ProductRow can skip re-rendering
  const handleSelect = useCallback((id) => setSelectedId(id), []);

  return (
    <>
      <p>Selected: {selectedId}</p>
      <ul>
        {visible.map((p) => (
          <ProductRow key={p.id} product={p} onSelect={handleSelect} />
        ))}
      </ul>
    </>
  );
}

Network optimization for faster response times

Finally, reduce what travels over the network:

  • Compress assets to cut payload size.
  • Split your code so each page loads only what it needs.
  • Lazy load anything that is not needed straight away.
  • Cache efficiently to improve perceived response speed.

For a deeper look at each of these, see Web Performance Optimization: A Practical Guide to Faster Sites.

Focus on these three areas and your applications stay snappy and responsive, which is the best user experience you can give.

Frequently asked questions

How can I make my code run faster?

Focus on three areas: choose efficient algorithms, prevent unnecessary re-renders in your UI, and reduce what you send over the network with compression, code splitting, lazy loading and caching.

Why is O(n log n) faster than O(n²)?

The work an O(n²) algorithm does grows with the square of the input size, while O(n log n) grows far more slowly. On large datasets, switching from one to the other can drastically reduce processing time.

When should I use React.memo, useMemo and useCallback?

Use them to stop unnecessary re-renders: React.memo to skip re-rendering a component whose props have not changed, useMemo for expensive computed values, and useCallback for functions you pass to memoized children.

Does caching make an app feel faster?

Yes. Efficient caching can significantly improve perceived response speed, alongside compression, code splitting and lazy loading.

All posts