weikee94 / design-patterns

Design Patterns
0 stars 0 forks source link

HOC pattern #12

Open weikee94 opened 11 months ago

weikee94 commented 11 months ago

withLoader

import React from 'react';
import { LoadingSpinner } from '../components/LoadingSpinner';

export default function withLoader(Element, url) {
  return (props) => {
    const [data, setData] = React.useState(null);

    React.useEffect(() => {
      fetch(url)
        .then((res) => res.json())
        .then((res) => setData(res));
    }, []);

    if (!data) return <LoadingSpinner />;

    return <Element {...props} data={data} />;
  };
}

Listings

import React from 'react';
import withLoader from '../../hoc/withLoader';
import { Listing } from './Listing';
import { ListingsGrid } from './ListingsGrid';

export function Listings(props) {
  return (
    <ListingsGrid>
      {props.data.listings.map((listing) => (
        <Listing key={listing.id} listing={listing} />
      ))}
    </ListingsGrid>
  );
}

export default withLoader(
  Listings,
  'https://house-lydiahallie.vercel.app/api/listings'
);

stackblitz

Here are the main points about the Higher-Order Component (HOC) pattern and its considerations:

Separation of Concerns

Naming Collisions

Readability

In summary, while Higher-Order Components offer benefits in terms of code organization and reusability, developers should be mindful of potential naming collisions and consider the impact on code readability, especially when using multiple HOCs in a single component. Balancing these considerations is crucial for effective use of the HOC pattern in React applications.