How to Fix React Higher-Order Component Issues
DodaTech
Updated 2026-06-26
1 min read
The Problem
In this quick-fix, you'll learn how to create HOCs that preserve display names statics and refs. This matters because HOCs lose original component display name and static methods. In real-world applications, this pattern appears in code reuse in auth logging and data fetching HOCs.
The Wrong Way
function withLogger(Wrapped) {
return class extends React.Component {
render() { return <Wrapped {...this.props} />; }
};
}
function Button(props) { return <button {...props} />; }
Button.someStatic = 'value';
const LoggedBtn = withLogger(Button);
LoggedBtn.displayName = '' (anonymous) static lost
The Right Way
import hoistNonReactStatics from 'hoist-non-react-statics';
function withLogger(Wrapped) {
class WithLogger extends React.Component {
render() { return <Wrapped {...this.props} />; }
}
WithLogger.displayName = 'withLogger(' + (Wrapped.displayName || Wrapped.name) + ')';
hoistNonReactStatics(WithLogger, Wrapped);
return React.forwardRef((props, ref) => <WithLogger {...props} forwardedRef={ref} />);
}
displayName = 'withLogger(Button)' static preserved
Prevention
- Set displayName on HOC wrapper
- Use hoist-non-react-statics for static methods
- Use forwardRef in HOCs for ref access
- Consider hooks as simpler HOC alternative
FAQ
This guide is brought to you by DodaTech — built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro