Hoist Non-React Statics

3.3.2 · active · verified Sun Apr 19

hoist-non-react-statics is a focused utility library for React applications designed to copy non-React specific static properties from a child component to a parent component. It functions similarly to `Object.assign` but intelligently blacklists React's internal static keywords to prevent unintentional overrides. This mechanism is critical for Higher-Order Components (HOCs) to correctly preserve static methods, `propTypes`, `defaultProps`, or other custom static properties from the wrapped component, preventing their loss during composition. The current stable version is 3.3.2. The package maintains a stable release cadence primarily driven by React's evolution (e.g., ForwardRefs support) and TypeScript definition enhancements, ensuring broad compatibility across various React versions. Its key differentiator is its precise targeting of user-defined static properties while respecting React's internals, solving a common HOC pattern challenge documented by React itself.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the core usage of `hoistNonReactStatics` within a Higher-Order Component (HOC) to transfer static methods and properties from a wrapped component to the HOC itself, preventing loss of functionality or metadata.

import hoistNonReactStatics from 'hoist-non-react-statics';
import React from 'react';

// Imagine a HOC that wraps a component
function withLogger(WrappedComponent) {
  class Logger extends React.Component {
    static displayName = `WithLogger(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;

    render() {
      console.log(`Rendering ${WrappedComponent.displayName || WrappedComponent.name}`);
      return <WrappedComponent {...this.props} />;
    }
  }

  // Crucially, hoist non-React statics from WrappedComponent to Logger
  // This ensures statics like propTypes, defaultProps, or custom static methods are preserved.
  return hoistNonReactStatics(Logger, WrappedComponent);
}

// Example usage:
class MyComponent extends React.Component {
  static someStaticMethod() {
    return 'Hello from static!';
  }
  render() {
    return <div>My Component Content</div>;
  }
}

const EnhancedComponent = withLogger(MyComponent);

console.log(EnhancedComponent.someStaticMethod()); // Should output 'Hello from static!'

view raw JSON →