Bad ways you’re using react – Higher Order Components

Share This Post

A common mistake made by React developers is to write all their logic and JSX into giant components. Copying and pasting code that is used in multiple places. As I explained in part 6, keeping your components small and concise has many benefits, and higher-order components, gives us another tool to shrink our component size.

 

What are higher-order components?

Higher Order Components (HOCs) are a pattern in React that allows you to reuse component logic by wrapping a component with a function that enhances its capabilities. A HOC is a function that takes a component and returns a new component with some additional functionality.

In other words, a HOC is a function that accepts a component as an argument and returns a new component that wraps the original component. This new component can then provide additional functionality to the original component, such as passing down props or managing state.

When would you use a higher-order component

You would use a Higher Order Component (HOC) in React when you need to reuse a certain functionality across multiple components, without having to repeat the same code in each component. HOCs can help you to keep your code DRY (Don’t Repeat Yourself), which makes your code easier to maintain and reduces the likelihood of bugs.

Some examples of when you might use a HOC include:

  1. Authentication: You can create a HOC that checks if the user is authenticated before rendering the wrapped component. This can be used across different pages or components that require authentication.
  2. Conditional Rendering: You can create a HOC that conditionally renders a component based on certain conditions. This can be useful if you need to display different content based on user roles or other criteria.
  3. Data Fetching: You can create a HOC that fetches data from an API and passes it down to the wrapped component as props. This can be useful if you have multiple components that need to fetch the same data.
  4. Logging or Analytics: You can create a HOC that logs user actions or sends data to an analytics service. This can be used across different components to track user behavior.

 

An example

import React from 'react';
import { Route, Switch, useLocation } from 'react-router-dom';

function App() {
  const location = useLocation();
  const isHomeScreen = location.pathname === '/';
  const isProductScreen = location.pathname.startsWith('/product/');

  return (
    <div>
      <Switch>
        <Route exact path="/">
          <div>
            {isHomeScreen && <h1>Welcome to our site!</h1>}
            <Home />
          </div>
        </Route>
        <Route path="/product/:id">
          <div>
            {isProductScreen && <h1>Welcome to our site!</h1>}
            <ProductDetail />
          </div>
        </Route>
        <Route path="/cart">
          <div>
            <Cart />
          </div>
        </Route>
      </Switch>
    </div>
  );
}

function Home() {
  return <h2>Home</h2>;
}

function ProductDetail() {
  return <h2>Product Detail</h2>;
}

function Cart() {
  return <h2>Cart</h2>;
}

In this example, the App component renders the Switch component that renders the appropriate component based on the current route. The banner is added inside the render method of each Route component, and is conditionally rendered based on whether the current route is the home screen or a product screen.

 

As an HOC

import React from 'react';
import { Route, Switch, withRouter } from 'react-router-dom';

function withBanner(WrappedComponent) {
  return function BanneredComponent(props) {
    const { location } = props;
    const isHomeScreen = location.pathname === '/';
    const isProductScreen = location.pathname.startsWith('/product/');

    return (
      <div>
        {(isHomeScreen || isProductScreen) && <h1>Welcome to our site!</h1>}
        <WrappedComponent {...props} />
      </div>
    );
  };
}

function Home() {
  return <h2>Home</h2>;
}

function ProductDetail() {
  return <h2>Product Detail</h2>;
}

function Cart() {
  return <h2>Cart</h2>;
}

const HomeWithBanner = withBanner(Home);
const ProductDetailWithBanner = withBanner(ProductDetail);
const CartWithBanner = withBanner(Cart);

function App() {
  return (
    <div>
      <Switch>
        <Route exact path="/" component={HomeWithBanner} />
        <Route path="/product/:id" component={ProductDetailWithBanner} />
        <Route path="/cart" component={CartWithBanner} />
      </Switch>
    </div>
  );
}

export default withRouter(App);

This code defines a React application with three routes: the home page, a product detail page, and a cart page. The withBanner function is a higher-order component that adds a banner to the top of the page if the user is on the home screen or a product detail screen. The Home, ProductDetail, and Cart functions are simple components that just display a title for their respective pages.

Leave a Reply

Digital art dealers

Join our vibrant community of more than 750 members by subscribing to our newsletter. Every Monday, you'll receive a programming meme to kickstart your week.

follow us on

© 2023 Digital Art Dealers. All rights reserved.

%d bloggers like this: