Back to Blog
ReactHOCPatternsComponents

React Higher-Order Components Guide

Master React Higher-Order Components for reusable component logic.

B
Bootspring Team
Engineering
July 23, 2018
6 min read

Higher-Order Components (HOCs) are functions that take a component and return a new enhanced component.

Basic HOC

Loading code block...

HOC with Configuration

Loading code block...

Injecting Props

Loading code block...

Display Name

Loading code block...

Forwarding Refs

Loading code block...

Composing HOCs

Loading code block...

Static Methods

Loading code block...

Error Boundary HOC

Loading code block...

Data Fetching HOC

Loading code block...

Conditional Rendering HOC

Loading code block...

HOCs vs Hooks

Loading code block...

Best Practices

HOC Design: ✓ Pass through unrelated props ✓ Set displayName for debugging ✓ Forward refs when needed ✓ Copy static methods Naming: ✓ Use 'with' prefix (withAuth, withData) ✓ Descriptive names ✓ Match injected prop names Performance: ✓ Don't create HOCs inside render ✓ Memoize when appropriate ✓ Avoid unnecessary re-renders Avoid: ✗ Mutating the original component ✗ Using HOCs inside render method ✗ HOC inside another HOC definition ✗ Over-nesting HOCs

Conclusion

Higher-Order Components provide a powerful pattern for reusing component logic. They wrap components to inject props, handle authentication, add error boundaries, and more. While hooks have replaced many HOC use cases, HOCs remain valuable for class components and certain composition patterns. Use compose for combining multiple HOCs, remember to forward refs and copy static methods, and consider hooks as a simpler alternative for functional components.

Share this article

Help spread the word about Bootspring

Related articles