DEV Community

Cover image for React: leveraging custom hooks to extract reusable logic
Reme Le Hane
Reme Le Hane

Posted on β€’ Originally published at remejuan.substack.com

React: leveraging custom hooks to extract reusable logic

Scenario: Fetching Data

Instead of repeatedly writing code for data fetching in every component, you can encapsulate that logic in a custom hook. This makes your code cleaner, reusable, and easy to maintain. Let’s walk through a simple example.

1. Create a Custom Hook for Data Fetching

import { useState, useEffect } from 'react';

// Custom hook to fetch data
function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        const result = await response.json();
        setData(result);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
}

export default useFetch;
Enter fullscreen mode Exit fullscreen mode

2. Use This Hook in Your Components

Now, you can use useFetch in any component to handle API data fetching:

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

function UserList() {
  const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/users');

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

  return (
    <ul>
      {data.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default UserList;
Enter fullscreen mode Exit fullscreen mode

Why This is Useful:

  • Separation of concerns: The logic for fetching data is separated from the component itself.
  • Reusability: You can use useFetch in multiple components without duplicating code.
  • Clarity: Components focus on rendering UI, making them simpler to understand.

πŸ”¨πŸ€–πŸ”§ Pro Tip: Custom hooks can do much more than just fetching data! You can use them for handling form inputs, subscriptions, or even implementing debouncing logic!

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay