Higher order function step by step guide

kurmivivek295

Vivek Kurmi

Posted on October 24, 2023

Higher order function step by step guide

A Higher-Order Component (HOC) in React is a function that takes a component and returns a new enhanced component with additional features or behavior. It's a technique that helps you keep your components clean and reusable by separating concerns. Think of it as a way to "wrap" components with extra capabilities, like adding authentication or data fetching, without changing the original components.

let's break down the Higher-Order Component (HOC) pattern step by step with code example:

Step 1: Problem - Mixing Authentication Logic with Components

Imagine you're building a website, and you want certain parts to be accessible only to users who have logged in. The problem is that the authentication logic is mixed directly into the components, making the code cluttered and hard to maintain.

Here's the code for the problematic component:

import React, { useState } from 'react';

function ProfilePage() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  const handleLogin = () => {
    setIsLoggedIn(true);
  }

  return (
    <div>
      {isLoggedIn ? (
        <div>
          <h2>Welcome to your profile</h2>
          <p>Here's your personal information...</p>
        </div>
      ) : (
        <div>
          <h2>Please log in to access this page</h2>
          <button onClick={handleLogin}>Log In</button>
        </div>
      )}
    </div>
  );
}

export default ProfilePage;
Enter fullscreen mode Exit fullscreen mode

This code mixes the authentication logic with the page content, making it challenging to maintain and reuse.

Step 2: Solution - Using a Higher-Order Component (HOC)

To tackle this problem, we can follow these steps:

Create an Authentication HOC:

import React, { useState } from 'react';

function withAuthentication(WrappedComponent) {
  return function () {
    const [isLoggedIn, setIsLoggedIn] = useState(false);

    const handleLogin = () => {
      setIsLoggedIn(true);
    }

    return (
      <div>
        {isLoggedIn ? (
          <WrappedComponent />
        ) : (
          <div>
            <h2>Please log in to access this page</h2>
            <button onClick={handleLogin}>Log In</button>
          </div>
        )}
      </div>
    );
  };
}

export default withAuthentication;
Enter fullscreen mode Exit fullscreen mode

In this code:

  • We create the withAuthentication HOC, which handles user authentication logic.
  • It checks if the user is logged in.
  • If the user is logged in, it renders the original component passed as WrappedComponent.
  • If the user is not logged in, it displays a message and a login button.

Use the HOC with a Protected Component:

import React from 'react';
import withAuthentication from './withAuthentication';

function ProfilePage() {
  return (
    <div>
      <h2>Welcome to your profile</h2>
      <p>Here's your personal information...</p>
    </div>
  );
}

const AuthenticatedProfilePage = withAuthentication(ProfilePage);

export default AuthenticatedProfilePage;
Enter fullscreen mode Exit fullscreen mode

In this part:

  • We have a component, ProfilePage, which we want to secure.
  • We wrap ProfilePage with the withAuthentication HOC to create AuthenticatedProfilePage.
  • Now, AuthenticatedProfilePage is protected by the authentication logic, and it will only be visible to authenticated users.

Summary:

  • The problem is about securing parts of a website for logged-in users. The initial code mixes authentication logic with page content, making it messy.
  • To solve this, we introduce a Higher-Order Component (HOC) called withAuthentication. It centralizes the authentication logic and determines who can access protected sections.
  • By wrapping a component with the HOC, we ensure that it's only accessible to authenticated users, keeping our code organized and eliminating repetitive authentication checks. It's like having a guard at the entrance who checks your credentials before letting you in.

šŸ˜ If you enjoy the content, please šŸ‘ like, šŸ”„ share, and šŸ‘£ follow for more updates!
Join me on a professional journey through my LinkedIn profile: Linkedin Profile

šŸ’– šŸ’Ŗ šŸ™… šŸš©
kurmivivek295
Vivek Kurmi

Posted on October 24, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related