Lesson 21-React Advanced Features

Advanced Hooks

Performance Optimization with useMemo and useCallback

useMemo Core Mechanism:

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  • Dependency Array: Recomputes only when dependencies change.
  • Caching Principle: Based on shallow comparison of dependencies.
  • Use Cases: Complex computations, preventing unnecessary child component renders.

useCallback Core Mechanism:

const memoizedCallback = useCallback(() => {
  doSomething(a, b);
}, [a, b]);
  • Function Memoization: Returns the same function reference if dependencies are unchanged.
  • Child Component Optimization: Works with React.memo to avoid unnecessary renders.
  • Typical Scenarios: Event handlers, callbacks passed to child components.

Performance Comparison Example:

// Unoptimized Version - Creates new function on every render
function Parent() {
  const handleClick = () => console.log('Click');
  return <Child onClick={handleClick} />;
}

// Optimized Version - Uses useCallback to maintain stable function reference
function Parent() {
  const handleClick = useCallback(() => console.log('Click'), []);
  return <Child onClick={handleClick} />;
}

useRef Usage and Considerations

Basic Usage:

const refContainer = useRef(initialValue);
  • DOM References: Access DOM nodes.
  • Persistent Values: Store mutable values across render cycles.
  • Difference from State: Modifying ref does not trigger re-renders.

Typical Use Cases:

// 1. DOM Manipulation
function TextInput() {
  const inputRef = useRef(null);
  const focusInput = () => inputRef.current.focus();
  return <input ref={inputRef} />;
}

// 2. Storing Previous Value
function Counter() {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef();
  useEffect(() => {
    prevCountRef.current = count;
  });
  const prevCount = prevCountRef.current;
  return <div>Now: {count}, Before: {prevCount}</div>;
}

Considerations:

  1. Avoid Overuse: Prioritize React state management.
  2. Async Risks: Ref values may be inconsistent between renders.
  3. Function Component Limitations: Cannot directly replace class instance properties.

useImperativeHandle with forwardRef

Combined Usage Pattern:

const FancyInput = forwardRef((props, ref) => {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current.focus(),
    scrollTo: () => inputRef.current.scrollIntoView()
  }));
  return <input ref={inputRef} {...props} />;
});

// Parent Component Usage
function Parent() {
  const inputRef = useRef();
  return (
    <>
      <FancyInput ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Focus</button>
    </>
  );
}

Implementation Principle:

  1. forwardRef: Forwards the parent’s ref to the child component.
  2. useImperativeHandle: Customizes the instance value exposed to the parent.
  3. Type Safety: Works with TypeScript to define clear interfaces.

useLayoutEffect vs. useEffect

Execution Timing Comparison:

FeatureuseEffectuseLayoutEffect
Execution PhaseAfter browser paintAfter DOM update, before browser paint
Use CasesData fetching, subscriptionsSynchronous DOM operations
Blocks RenderingNoYes
Server-Side RenderingSupportedWarns (avoid use)

Typical Use Cases:

// useEffect - Asynchronous Operations
useEffect(() => {
  fetchData().then(data => setData(data));
}, []);

// useLayoutEffect - Synchronous DOM Measurement
useLayoutEffect(() => {
  const width = element.current.offsetWidth;
  setDimensions({ width });
}, [deps]);

Custom Hook Design Patterns

Data Fetching Pattern:

function useFetch(url, options) {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url, options);
        const result = await response.json();
        setData(result);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [url, options]);

  return { data, error, loading };
}

Subscription Pattern:

function useSubscription(eventBus, eventName, callback) {
  useEffect(() => {
    eventBus.subscribe(eventName, callback);
    return () => eventBus.unsubscribe(eventName, callback);
  }, [eventBus, eventName, callback]);
}

Design Principles:

  1. Single Responsibility: Each Hook focuses on a specific function.
  2. Composability: Supports combination with other Hooks.
  3. Clear Dependencies: Correctly declare all dependencies.
  4. Type Safety: Use TypeScript for clear interfaces.

Component Performance Optimization

Virtual DOM and Diff Algorithm Optimization

React Diff Strategies:

  1. Tree Comparison: Compares same-level nodes; cross-level moves are costly.
  2. Component Type: Different types result in destruction and recreation.
  3. Key Property: Unique identifier for list items.

Optimization Tips:

// Bad Practice - Creates new array on every render
function BadList() {
  const items = Array(1000).fill().map((_, i) => i);
  return <List items={items} />;
}

// Good Practice - Stable reference
function GoodList() {
  const items = useMemo(() => Array(1000).fill().map((_, i) => i), []);
  return <List items={items} />;
}

React.memo and PureComponent

React.memo Implementation:

const MemoizedComponent = React.memo(function MyComponent(props) {
  /* Render logic */
}, arePropsEqual);

// Custom comparison function
function arePropsEqual(prevProps, nextProps) {
  return prevProps.id === nextProps.id;
}

PureComponent Principle:

  • Automatically performs shallow comparison of props and state.
  • Suitable for class components.
  • Avoids manual shouldComponentUpdate implementation.

Usage Scenario Comparison:

ScenarioReact.memoPureComponent
Component TypeFunction componentsClass components
Comparison ControlCustom comparison functionDefault shallow comparison
Applicable VersionReact 16.6+All versions

List Rendering Optimization

Key Selection Principles:

  1. Stability: Unique identifiers that don’t change across renders.
  2. Predictability: Same input produces the same key.
  3. Avoid Index: Avoid using array indices for dynamic lists.

Virtual List Implementation:

import { FixedSizeList as List } from 'react-window';

function BigList({ items }) {
  return (
    <List
      height={600}
      itemCount={items.length}
      itemSize={50}
      width="100%"
    >
      {({ index, style }) => (
        <div style={style}>
          {items[index].name}
        </div>
      )}
    </List>
  );
}

Optimization Techniques:

  1. Pagination loading.
  2. Windowed rendering (react-window).
  3. Avoid inline functions.
  4. Use CSS containment.

Code Splitting and Lazy Loading

React.lazy Implementation:

const LazyComponent = React.lazy(() => import('./LazyComponent'));

function App() {
  return (
    <Suspense fallback={<LoadingSpinner />}>
      <LazyComponent />
    </Suspense>
  );
}

Route-Level Code Splitting:

const Home = React.lazy(() => import('./routes/Home'));
const About = React.lazy(() => import('./routes/About'));

function App() {
  return (
    <Router>
      <Suspense fallback={<Loading />}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
        </Routes>
      </Suspense>
    </Router>
  );
}

Preloading Strategy:

// Preload on hover
const LazyComponent = React.lazy(() => import('./LazyComponent'));

function HoverLoader() {
  const [preload, setPreload] = useState(false);

  return (
    <div 
      onMouseEnter={() => setPreload(true)}
      onMouseLeave={() => setPreload(false)}
    >
      {preload && <LazyComponent />}
    </div>
  );
}

Memory Leaks and Resource Cleanup

Common Leak Scenarios:

  1. Uncleaned timers.
  2. Uncancelled subscriptions.
  3. Unreleased DOM events.
  4. Unaborted Promises.

Cleanup Pattern Examples:

// Timer Cleanup
useEffect(() => {
  const timer = setInterval(() => {
    // ...
  }, 1000);
  return () => clearInterval(timer);
}, []);

// Subscription Cleanup
useEffect(() => {
  const subscription = eventBus.subscribe(callback);
  return () => subscription.unsubscribe();
}, []);

// AbortController for Request Cancellation
useEffect(() => {
  const controller = new AbortController();
  fetch(url, { signal: controller.signal })
    .then(/* ... */)
    .catch(e => {
      if (e.name !== 'AbortError') {
        // Handle real errors
      }
    });
  return () => controller.abort();
}, [url]);

Higher-Order Components and Render Props

Definition and Implementation of Higher-Order Components (HOC)

Basic HOC Pattern:

function withLogging(WrappedComponent) {
  return function EnhancedComponent(props) {
    console.log('Props:', props);
    return <WrappedComponent {...props} />;
  };
}

// Usage
const EnhancedComponent = withLogging(MyComponent);

Parameterized HOC:

function withDataFetching(url) {
  return function(WrappedComponent) {
    return function EnhancedComponent(props) {
      const [data, setData] = useState(null);
      useEffect(() => {
        fetchData(url).then(setData);
      }, [url]);
      return <WrappedComponent data={data} {...props} />;
    };
  };
}

HOC Use Cases

Typical Applications:

  1. Authorization Control:
function withAuth(WrappedComponent) {
  return function AuthenticatedComponent(props) {
    const { user } = useAuth();
    return user ? <WrappedComponent {...props} /> : <Redirect to="/login" />;
  };
}
  1. Performance Monitoring:
function withPerformance(WrappedComponent) {
  return function MonitoredComponent(props) {
    const start = performance.now();
    useEffect(() => {
      const duration = performance.now() - start;
      logRenderTime(WrappedComponent.name, duration);
    }, []);
    return <WrappedComponent {...props} />;
  };
}
  1. Theme Injection:
function withTheme(WrappedComponent) {
  return function ThemedComponent(props) {
    const theme = useTheme();
    return <WrappedComponent theme={theme} {...props} />;
  };
}

Render Props Pattern and Usage

Classic Render Props Implementation:

class MouseTracker extends React.Component {
  state = { x: 0, y: 0 };

  handleMouseMove = (event) => {
    this.setState({ x: event.clientX, y: event.clientY });
  };

  render() {
    return (
      <div onMouseMove={this.handleMouseMove}>
        {this.props.render(this.state)}
      </div>
    );
  }
}

// Usage
<MouseTracker render={({ x, y }) => (
  <h1>Mouse position: {x}, {y}</h1>
)} />

Function Component Implementation:

function MouseTracker({ render }) {
  const [position, setPosition] = useState({ x: 0, y: 0 });

  useEffect(() => {
    const handleMouseMove = (e) => {
      setPosition({ x: e.clientX, y: e.clientY });
    };
    document.addEventListener('mousemove', handleMouseMove);
    return () => document.removeEventListener('mousemove', handleMouseMove);
  }, []);

  return render(position);
}

HOC vs. Render Props Comparison

FeatureHOCRender Props
Code OrganizationHorizontal composition (wraps component)Vertical composition (nested rendering)
ReadabilityMay cause “wrapper hell”Clearer rendering flow
Learning CurveSimplerRequires understanding render prop concept
TypeScript SupportNeeds complex type definitionsMore direct type inference
PerformanceMay add component nestingRenders target component directly

Best Practices for Compositional Development

Mixed Usage Pattern:

// Enhance base component with HOCs
const EnhancedComponent = withLogging(withTheme(MyComponent));

// Use Render Props during rendering
<EnhancedComponent render={({ theme }) => (
  <div style={{ background: theme.background }}>
    {/* Content */}
  </div>
)} />

Modern Alternatives:

  1. Hooks: Replace most HOC and Render Props scenarios.
  2. Compound Components: Build complex UIs via component composition.
  3. Context API: Share global state.

Design Principles:

  1. Single Responsibility: Each HOC/Render Prop focuses on one function.
  2. Clear Interfaces: Define clear props and render callbacks.
  3. Avoid Over-Abstraction: Use advanced patterns only when necessary.
  4. Type Safety: Ensure type correctness with TypeScript.

Share your love