Building Custom Hooks

Learn how to create reusable logic in React by building custom hooks.

1. What are Custom Hooks?

Custom hooks are JavaScript functions that allow you to reuse logic across multiple components in React. They follow the same rules as built-in hooks and often simplify code by abstracting stateful logic.

2. Why Use Custom Hooks?

  • Code Reusability: Share stateful logic between components without duplicating code.
  • Improved Readability: Simplify component structure by moving logic into hooks.
  • Testability: Isolate logic for easier testing.

3. Example: Creating a Custom Hook

Here’s an example of a custom hook for fetching data:

import { useState, useEffect } from 'react';

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

    useEffect(() => {
        fetch(url)
            .then(response => response.json())
            .then(data => {
                setData(data);
                setLoading(false);
            })
            .catch(error => {
                setError(error);
                setLoading(false);
            });
    }, [url]);

    return { data, loading, error };
}

export default useFetch;
                

Explanation: The useFetch hook encapsulates the logic for fetching data, allowing components to focus on rendering.

4. Using the Custom Hook

Here’s how to use the useFetch hook in a component:

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

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

    if (loading) return 

Loading...

; if (error) return

Error: {error.message}

; return (

Fetched Data:

{JSON.stringify(data, null, 2)}
); } export default App;

Explanation: The component uses the useFetch hook to fetch data and handle loading and error states.

5. Best Practices

  • Prefix with "use": Always start hook names with "use" to follow React conventions.
  • Keep Hooks Focused: Each hook should handle a single piece of functionality.
  • Use Dependencies: Ensure proper dependency arrays in useEffect to avoid infinite loops.

Additional Resources