Menu

How to Use Lazy Loading in React for Faster Performance

Slow initial load times can drive users away from your React application. One powerful technique to improve performance is lazy loading - loading components only when they're needed.

Let's explore how to implement this in React.

The Problem with Eager Loading

By default, React bundles all your components together, forcing users to download everything upfront. This makes navigation much quicker and more streamlined once this initial download is complete.

However, depending on the size of your application, it could also create a long initial load time.

import HeavyComponent from './HeavyComponent';
import AnotherHeavyComponent from './AnotherHeavyComponent';

function App() {
  return (
    <div>
      {/* These components load even if user never sees them */}
      <HeavyComponent />
      <AnotherHeavyComponent />
    </div>
  );
}

React.lazy() to the Rescue

React.lazy() lets you defer loading components until they're actually needed:

import React, { lazy, Suspense } from 'react';

// Components are now loaded only when rendered
const HeavyComponent = lazy(() => import('./HeavyComponent'));
const AnotherHeavyComponent = lazy(() => import('./AnotherHeavyComponent'));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <HeavyComponent />
        <AnotherHeavyComponent />
      </Suspense>
    </div>
  );
}

Route-Based Lazy Loading

Combine with React Router for even better performance:

import React, { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';

const Home = lazy(() => import('./pages/Home'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Settings = lazy(() => import('./pages/Settings'));

function App() {
  return (
    <BrowserRouter>
      <Suspense fallback={<div>Loading...</div>}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/dashboard" element={<Dashboard />} />
          <Route path="/settings" element={<Settings />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}

Implement these techniques in your React application today and watch your load times improve dramatically!

0
73

Related

Removing duplicates from a list in C# is a common task, especially when working with large datasets. C# provides multiple ways to achieve this efficiently, leveraging built-in collections and LINQ.

Using HashSet (Fastest for Unique Elements)

A HashSet<T> automatically removes duplicates since it only stores unique values. This is one of the fastest methods:

List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5 };
numbers = new HashSet<int>(numbers).ToList();
Console.WriteLine(string.Join(", ", numbers)); // Output: 1, 2, 3, 4, 5

Using LINQ Distinct (Concise and Readable)

LINQ’s Distinct() method provides an elegant way to remove duplicates:

List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5 };
numbers = numbers.Distinct().ToList();
Console.WriteLine(string.Join(", ", numbers)); // Output: 1, 2, 3, 4, 5

Removing Duplicates by Custom Property (For Complex Objects)

When working with objects, DistinctBy() from .NET 6+ simplifies duplicate removal based on a property:

using System.Linq;
using System.Collections.Generic;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

List<Person> people = new List<Person>
{
    new Person { Name = "Alice", Age = 30 },
    new Person { Name = "Bob", Age = 25 },
    new Person { Name = "Alice", Age = 30 }
};

people = people.DistinctBy(p => p.Name).ToList();
Console.WriteLine(string.Join(", ", people.Select(p => p.Name))); // Output: Alice, Bob

For earlier .NET versions, use GroupBy():

people = people.GroupBy(p => p.Name).Select(g => g.First()).ToList();

Performance Considerations

  • HashSet<T> is the fastest but only works for simple types.
  • Distinct() is easy to use but slower than HashSet<T> for large lists.
  • DistinctBy() (or GroupBy()) is useful for complex objects but may have performance trade-offs.

Conclusion

Choosing the best approach depends on the data type and use case. HashSet<T> is ideal for primitive types, Distinct() is simple and readable, and DistinctBy() (or GroupBy()) is effective for objects.

0
75

XML (Extensible Markup Language) is a widely used format for storing and transporting data.

In C#, you can create XML files efficiently using the XmlWriter and XDocument classes. This guide covers both methods with practical examples.

Writing XML Using XmlWriter

XmlWriter provides a fast and memory-efficient way to generate XML files by writing elements sequentially.

Example:

using System;
using System.Xml;

class Program
{
    static void Main()
    {
        using (XmlWriter writer = XmlWriter.Create("person.xml"))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("Person");

            writer.WriteElementString("FirstName", "John");
            writer.WriteElementString("LastName", "Doe");
            writer.WriteElementString("Age", "30");

            writer.WriteEndElement();
            writer.WriteEndDocument();
        }
        Console.WriteLine("XML file created successfully.");
    }
}

Output (person.xml):

<?xml version="1.0" encoding="utf-8"?>
<Person>
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
    <Age>30</Age>
</Person>

Writing XML Using XDocument

The XDocument class from LINQ to XML provides a more readable and flexible way to create XML files.

Example:

using System;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        XDocument doc = new XDocument(
            new XElement("Person",
                new XElement("FirstName", "John"),
                new XElement("LastName", "Doe"),
                new XElement("Age", "30")
            )
        );
        doc.Save("person.xml");
        Console.WriteLine("XML file created successfully.");
    }
}

This approach is ideal for working with complex XML structures and integrating LINQ queries.

When to Use Each Method

  • Use XmlWriter when performance is critical and you need to write XML sequentially.
  • Use XDocument when you need a more readable, maintainable, and flexible way to manipulate XML.

Conclusion

Writing XML files in C# is straightforward with XmlWriter and XDocument. Choose the method that best suits your needs for performance, readability, and maintainability.

1
64

The null coalescing assignment operator (??=) introduced in C# 8.0 provides a cleaner way to assign a value to a variable only when it's null. Let's see how and when to use it effectively.

Quick Example

// Instead of writing this:
if (myVariable == null)
    myVariable = defaultValue;

// You can write this:
myVariable ??= defaultValue;

Real-World Examples

Simple Property Initialization

public class UserSettings
{
    private List<string> _preferences;
    
    public List<string> Preferences
    {
        get
        {
            _preferences ??= new List<string>();
            return _preferences;
        }
    }
}

Service Caching

public class ServiceCache
{
    private ApiClient _client;
    
    public ApiClient GetClient()
    {
        _client ??= new ApiClient("https://api.example.com");
        return _client;
    }
}

Lazy Configuration Loading

public class ConfigurationManager
{
    private Dictionary<string, string> _settings;
    
    public string GetSetting(string key)
    {
        _settings ??= LoadSettingsFromFile();
        return _settings.TryGetValue(key, out var value) ? value : null;
    }
    
    private Dictionary<string, string> LoadSettingsFromFile()
    {
        // Load settings logic here
        return new Dictionary<string, string>();
    }
}

Common Gotchas

Reference vs Value Types

The operator works differently with value types - they need to be nullable:

// This won't compile
int count ??= 1;

// This works
int? count ??= 1;

Chaining Operations

// You can chain the operator
string result = first ??= second ??= "default";

// Equivalent to:
if (first == null)
{
    if (second == null)
    {
        second = "default";
    }
    first = second;
}
result = first;

Thread Safety

The operator is not thread-safe by default:

// Not thread-safe
public class SharedCache
{
    private static Dictionary<string, object> _cache;
    
    public object GetItem(string key)
    {
        // Multiple threads could evaluate null simultaneously
        _cache ??= new Dictionary<string, object>();
        return _cache.GetValueOrDefault(key);
    }
}

// Thread-safe version
public class SharedCache
{
    private static Dictionary<string, object> _cache;
    private static readonly object _lock = new object();
    
    public object GetItem(string key)
    {
        lock (_lock)
        {
            _cache ??= new Dictionary<string, object>();
            return _cache.GetValueOrDefault(key);
        }
    }
}

Performance Considerations

The null coalescing assignment operator is compiled to efficient IL code. It generally performs the same as an explicit null check:

// These compile to similar IL
obj ??= new object();

if (obj == null)
    obj = new object();

When to Use It

✅ Good use cases:

  • Lazy initialization of properties
  • Caching values
  • Setting default values for nullable types
  • Simplifying null checks in property getters

❌ Avoid using when:

  • You need thread-safe initialization (use Lazy<T> instead)
  • The right-hand expression has side effects
  • You need more complex null-checking logic

Visual Studio Tips

You can use Quick Actions (Ctrl+.) to convert between traditional null checks and the ??= operator. Look for the suggestion "Use null coalescing assignment" when you have a pattern like:

if (variable == null)
    variable = value;

Version Compatibility

This feature requires:

  • C# 8.0 or later
  • .NET Core 3.0+ or .NET Standard 2.1+
  • Visual Studio 2019+
1
49