Modern React Patterns: Advanced Hooks, State Management, and Performance

On this page

Table of contents

    React’s component model has matured from imperative class components with convoluted lifecycle methods to an elegant, declarative functional paradigm powered by hooks. Building maintainable applications at scale requires understanding not only how hooks work, but also when and how to avoid costly re-render cascades.

    Encapsulating Logic with Reusable Custom Hooks

    Custom hooks allow engineering teams to extract stateful logic into modular, testable units across different screens. A classic example is synchronized persistent storage:

    import { useState, useEffect } from 'react';
    
    export function useLocalStorage<T>(key: string, initialValue: T): [T, (val: T | ((prev: T) => T)) => void] {
      const [storedValue, setStoredValue] = useState<T>(() => {
        try {
          const item = window.localStorage.getItem(key);
          return item ? JSON.parse(item) : initialValue;
        } catch (error) {
          console.warn(`Error reading localStorage key "${key}":`, error);
          return initialValue;
        }
      });
    
      useEffect(() => {
        try {
          window.localStorage.setItem(key, JSON.stringify(storedValue));
        } catch (error) {
          console.error(`Error saving localStorage key "${key}":`, error);
        }
      }, [key, storedValue]);
    
      return [storedValue, setStoredValue];
    }

    Eliminating Unnecessary Re-Renders

    Premature optimization is a known trap, but unoptimized context providers can degrade UI fluidity across entire apps. To optimize component trees:

    • Split Contexts: Separate frequently changing data (like active user inputs) from static dispatch actions.
    • Memoize Heavy Calculations: Wrap computationally expensive transformations in useMemo.
    • Memoize Callbacks: Stabilize prop references passed to memoized children using useCallback.

    Leave a Reply