Skip to main content

How To React Custom Hooks: Unlocking Reusability and Efficiency

When you're developing with React, there comes a time when you want to reuse logic across multiple components. 

It can feel like déjà vu as you copy-paste code. 

This is where React custom hooks come to the rescue, offering a way to encapsulate and reuse logic without redundancy.

Why Use Custom Hooks?

Custom hooks are like crafting your own building blocks. 

They help streamline your code and reduce duplication, much like decluttering a messy workspace. 

But why should you invest time in learning to create them?

  1. Reusability: Custom hooks let you extract component logic into reusable functions. This means fewer bugs since you fix a problem in one place.

  2. Clean Code: By separating logic from UI, you keep components focused on rendering. Cleaner code is easier to read and maintain.

  3. Testability: Hooks segregate logic, making it straightforward to test using unit tests.

Doesn't it sound so much better than managing tangled webs of code?

Creating Your First Custom Hook

To demystify custom hooks, let's create a hook that fetches data. We'll call it useFetch. This hook will make an API call and return the response. Here’s a step-by-step guide:

Step 1: Set Up the Basic Hook Structure

Think of this as laying the foundation. First, create a function named useFetch.

import { useState, useEffect } from 'react';

function useFetch(url) {
  // State hooks for data, loading, and error
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Fetch data from the API
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        if (!response.ok) throw new Error('Network response was not ok');
        const result = await response.json();
        setData(result);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]); // Dependency array ensures effect only runs when URL changes

  return { data, loading, error };
}

export default useFetch;

Step 2: Define the Logic

Inside the useFetch, use useEffect and useState to handle fetching data. useEffect runs the function when the component mounts and when URL changes.

  • useState Hook: Manages data, loading, and error. Initially, data is null, loading is true, and error is null.

  • useEffect Hook: Asynchronously fetches data and updates state. It's a side-effect as it interacts with the outside world.

Step 3: Handle the API Logic

Within useEffect, the fetchData function handles API calls.

  • Fetching Data: It uses the fetch API to get data. The await keyword ensures the code waits for the API's response.

  • Error Handling: If the response isn't OK, an error is thrown. This error is caught in the catch block, setting setError.

Step 4: Return the Values

Finally, useFetch returns an object containing data, loading, and error. This will be consumed by components using this hook.

Using the Custom Hook in a Component

Once you've got your custom hook ready, the next step is using it in a React component.

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

function App() {
  const { data, loading, error } = useFetch('https://api.example.com/data');

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h1>Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default App;

Component Breakdown

  • Loading State: An initial check for loading displays a message while data is being fetched.
  • Error Handling: If there's an error, it renders an error message.
  • Data Display: Once loading is complete and there's no error, it displays the fetched data.

Best Practices for Custom Hooks

When writing custom hooks, be sure to stick to a few principles:

  1. Prefix with ‘use’: By using use, you ensure React recognizes the function as a hook, applying its rules correctly.

  2. Consistency: Follow a naming convention and ensure hooks encapsulate a single piece of logic.

  3. Avoid Interdependent Hooks: Hooks should not depend on the state of others. Each should be self-contained.

Crafting custom hooks is like creating specialized tools for your toolbox. 

They allow you to keep your code DRY (Don't Repeat Yourself) and focused. 

Once you embrace them, you'll find yourself writing React components that are easier to read and maintain. 

And who doesn't love code that feels like a well-oiled machine?

Popular posts from this blog

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

Linux Network Troubleshooting

If you've spent any time as a sysadmin — or honestly, just as someone who's had to fix their own home network at 11pm — you know that connectivity issues are one of the most common headaches out there. The good news is that a handful of core tools and a methodical approach can take you from "why isn't this working" to a root cause pretty quickly.  This guide walks through the essentials: configuring interfaces, managing routes, and diagnosing problems when things go sideways. Configuring Network Interfaces Your network interfaces are the actual bridge between your machine and the outside world, so getting them configured correctly is step one for any kind of reliable connectivity. Doing It Manually ifconfig is the old-school, tried-and-true tool for this on Unix-like systems. To see everything currently configured, run: ifconfig -a If you need to manually set up a specific interface — assigning an IP, a netmask, and bringing it online — it looks like this: ifconf...