What are higher order components in React?
TL;DR
Higher order components (HOCs) in React are functions that take a component and return a new component with additional props or behavior. They are used to reuse component logic. For example, if you have a component MyComponent
, you can create an HOC like this:
const withExtraProps = (WrappedComponent) => {return (props) => <WrappedComponent {...props} extraProp="value" />;};const EnhancedComponent = withExtraProps(MyComponent);
What are higher order components in React?
Definition
Higher order components (HOCs) are functions in React that take a component as an argument and return a new component. The new component typically wraps the original component and adds additional props, state, or behavior. HOCs are a pattern for reusing component logic.
Purpose
HOCs are used to:
- Share common functionality between components
- Abstract and reuse component logic
- Enhance components with additional props or state
Example
Here is a simple example of an HOC that adds an extraProp
to a wrapped component:
import React from 'react';// Define the HOCconst withExtraProps = (WrappedComponent) => {return (props) => {return <WrappedComponent {...props} extraProp="value" />;};};// Define a component to be wrappedconst MyComponent = (props) => {return <div>{props.extraProp}</div>;};// Wrap the component using the HOCconst EnhancedComponent = withExtraProps(MyComponent);// Use the enhanced componentconst App = () => {return <EnhancedComponent />;};export default App;
In this example, withExtraProps
is an HOC that adds an extraProp
to MyComponent
. The EnhancedComponent
now has access to extraProp
.
Common use cases
- Authentication: Wrapping components to check if a user is authenticated before rendering.
- Logging: Adding logging functionality to components.
- Theming: Injecting theme-related props into components.
- Data fetching: Fetching data and passing it as props to components.
Best practices
- Do not mutate the original component: Always return a new component.
- Use HOCs sparingly: Overusing HOCs can make the code harder to understand.
- Name the HOC properly: Use a descriptive name that indicates what the HOC does.
Alternatives
- Render props: A pattern where a component uses a function as a prop to determine what to render.
- Hooks: Custom hooks can be used to share logic between functional components.