Custom Hooks vs HOC in React/React Native

abdul ahad
4 min read5 days ago

--

Photo by Neil Kami on Unsplash

In React, both Custom Hooks and Higher-Order Components (HOC) are powerful tools for reusing logic across components. However, they have different characteristics and use cases. Let’s break down their differences, when to use each, and how they compare.

Custom Hooks

Definition:
A custom hook is a function in React that allows you to reuse logic across multiple functional components. It starts with use (like useState, useEffect) and can leverage React's built-in hooks or other hooks.

Advantages of Custom Hooks:

  1. Readability and Simplicity: Custom hooks allow you to reuse logic in a more readable and simpler way, especially with functional components.
  2. Better TypeScript Support: Hooks integrate smoothly with TypeScript for type inference and checking.
  3. Composable: Hooks can be easily composed by using other hooks within them. You can build complex behavior by combining smaller hooks.
  4. Encapsulation of Side Effects: Hooks can be used to encapsulate side effects such as data fetching, subscribing to events, or managing timers.

When to Use Custom Hooks:

  • Stateful Logic Reuse: Whenever you need to share logic that involves state or side effects (e.g., fetching data, managing timers) across multiple components.
  • Side Effect Management: For managing side effects such as fetching API data, subscriptions, etc., in functional components.

Example: Custom Hook for Fetching Data

import { useState, useEffect } from 'react';

// Custom Hook
const useFetchData = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
const fetchData = async () => {
const response = await fetch(url);
const result = await response.json();
setData(result);
setLoading(false);
};

fetchData();
}, [url]);

return { data, loading };
};

// Usage in a functional component
const MyComponent = () => {
const { data, loading } = useFetchData('https://api.example.com/data');

if (loading) return <p>Loading...</p>;

return <div>{data && data.map(item => <p key={item.id}>{item.name}</p>)}</div>;
};

Key Points of Custom Hooks:

  • Reusable: Can be used in any functional component.
  • Simple API: They don’t require additional component layers, unlike HOCs.
  • Functional: Only applicable to functional components, as hooks cannot be used in class components.

Higher-Order Components (HOC)

Definition:
A Higher-Order Component (HOC) is a function that takes a component and returns a new component with additional props or behavior. It is used to add functionality to existing components without modifying them directly.

Advantages of HOCs:

  1. Component Wrapping: HOCs can wrap a component and inject additional props, providing an easy way to share functionality.
  2. Reusability Across Different Component Types: HOCs can be used with both class and functional components.
  3. Prop Injection: They allow for prop injection or prop manipulation, which is useful when you want to add common behavior (e.g., authentication, logging, error handling) to multiple components.

When to Use HOCs:

  • Enhancing Components: When you need to enhance components by adding props or behavior (e.g., injecting context, applying conditional rendering, managing lifecycle).
  • Cross-Cutting Concerns: For tasks like authorization, analytics, error boundaries, etc., which may involve wrapping a component with additional logic.

Example: HOC for Authentication

import React from 'react';

// Higher-Order Component for authentication
const withAuth = (WrappedComponent) => {
return (props) => {
const isAuthenticated = !!localStorage.getItem('token');
if (!isAuthenticated) {
return <p>You need to log in to access this page.</p>;
}
return <WrappedComponent {...props} />;
};
};

// Usage with a component
const Dashboard = () => <p>Welcome to the dashboard!</p>;

export default withAuth(Dashboard); // Dashboard component is now wrapped with authentication check

Key Points of HOCs:

  • Can Be Used with Any Component Type: Unlike custom hooks, HOCs can be applied to both class and functional components.
  • Add a Component Layer: HOCs wrap components, which adds an extra layer to the component tree. This can make debugging more complex.
  • Prop Manipulation: HOCs often manipulate or add props to components, giving them additional power in terms of enhancing behavior.
  • Naming Conflicts: You may run into prop or naming conflicts when multiple HOCs are used together.

Custom Hooks vs. HOCs: A Comparison

A chatGPT reference:

When to Use Custom Hooks:

  • When you need to share stateful logic between multiple components (e.g., handling state, side effects, fetching data, timers).
  • You want to reuse logic without adding an additional layer of components.
  • In functional components where hooks are supported, making custom hooks the natural choice.

When to Use HOCs:

  • When you need to augment a component by adding additional props or wrapping it with logic that should apply to many components (e.g., authentication, conditional rendering).
  • If you are working with class components or need to support both class and functional components.
  • When you need to inject context or modify props in a way that involves manipulating the component at a higher level.

--

--

abdul ahad

A software developer dreaming to reach the top and also passionate about sports and language learning