HOC vs Render Props
When it comes to state management in React, two popular patterns are Higher-Order Components (HOCs) and Render Props. Both patterns are used to share data or behavior between components, but they have different approaches.
Higher-Order Components (HOCs)
In React, a Higher-Order Component is a function that takes a component as an argument and returns a new component. The HOC wraps the original component and provides additional props or behavior.
Here's an example of a Higher-Order Component that adds a loading
prop to a component:
JAVASCRIPT
1function withLoading(Component) {
2 return function WithLoading(props) {
3 const [isLoading, setLoading] = useState(true);
4
5 useEffect(() => {
6 // Simulating an API request
7 setTimeout(() => setLoading(false), 2000);
8 }, []);
9
10 return isLoading ? <p>Loading...</p> : <Component {...props} />;
11 };
12}
13
14const MyComponent = ({ data }) => (
15 <div>
16 <h1>My Component</h1>
17 <p>Data: {data}</p>
18 </div>
19);
20
21const MyComponentWithLoading = withLoading(MyComponent);