⚛️ React Custom Hooks

Chapter 15 of 15

What are Custom Hooks?

Custom Hooks are reusable functions that contain stateful logic. When you have component logic that needs to be used by multiple components, you can extract that logic to a custom Hook.

💡 Key Point: Custom Hooks allow you to reuse stateful logic between components without changing your component hierarchy!

Naming Convention

Custom Hooks must start with "use" (e.g., useFetch, useLocalStorage, useAuth).

⚠️ Important: The "use" prefix is required! This tells React that the function follows the rules of Hooks.

Creating a Custom Hook

Let's create a custom hook for fetching data:

useFetch.js

import { useState, useEffect } from "react";

const useFetch = (url) => {
  const [data, setData] = useState(null);
  const [isPending, setIsPending] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    setTimeout(() => {
      fetch(url)
        .then(res => {
          if (!res.ok) {
            throw Error('Could not fetch the data');
          }
          return res.json();
        })
        .then(data => {
          setIsPending(false);
          setData(data);
          setError(null);
        })
        .catch(err => {
          setIsPending(false);
          setError(err.message);
        })
    }, 1000);
  }, [url]);

  return { data, isPending, error };
}

export default useFetch;

Using a Custom Hook

Now you can use this custom hook in any component:

Home.js

import useFetch from "./useFetch";

const Home = () => {
  const { data: blogs, isPending, error } = useFetch('http://localhost:8000/blogs');

  return (
    <div className="home">
      { error && <div>{ error }</div> }
      { isPending && <div>Loading...</div> }
      { blogs && <BlogList blogs={blogs} /> }
    </div>
  );
}

export default Home;
✨ Reusable: You can now use useFetch in any component that needs to fetch data!

More Custom Hook Examples

1. useLocalStorage

Store and retrieve values from localStorage:

import { useState, useEffect } from "react";

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const item = localStorage.getItem(key);
    return item ? JSON.parse(item) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

// Usage
function App() {
  const [name, setName] = useLocalStorage('name', '');

  return (
    <input
      value={name}
      onChange={(e) => setName(e.target.value)}
      placeholder="Enter your name"
    />
  );
}

2. useWindowSize

Track window dimensions:

import { useState, useEffect } from "react";

function useWindowSize() {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  useEffect(() => {
    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight
      });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return windowSize;
}

// Usage
function App() {
  const { width, height } = useWindowSize();

  return (
    <div>
      Window size: {width} x {height}
    </div>
  );
}

3. useToggle

Simple boolean toggle:

import { useState } from "react";

function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);

  const toggle = () => {
    setValue(prev => !prev);
  };

  return [value, toggle];
}

// Usage
function App() {
  const [isVisible, toggleVisible] = useToggle(false);

  return (
    <div>
      <button onClick={toggleVisible}>Toggle</button>
      {isVisible && <div>Content is visible!</div>}
    </div>
  );
}

4. useDebounce

Delay updates (useful for search):

import { useState, useEffect } from "react";

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

// Usage
function SearchComponent() {
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 500);

  useEffect(() => {
    if (debouncedSearchTerm) {
      // API call here
      console.log('Searching for:', debouncedSearchTerm);
    }
  }, [debouncedSearchTerm]);

  return (
    <input
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
      placeholder="Search..."
    />
  );
}

5. useOnClickOutside

Detect clicks outside an element:

import { useEffect } from "react";

function useOnClickOutside(ref, handler) {
  useEffect(() => {
    const listener = (event) => {
      if (!ref.current || ref.current.contains(event.target)) {
        return;
      }
      handler(event);
    };

    document.addEventListener('mousedown', listener);
    document.addEventListener('touchstart', listener);

    return () => {
      document.removeEventListener('mousedown', listener);
      document.removeEventListener('touchstart', listener);
    };
  }, [ref, handler]);
}

// Usage
function DropdownMenu() {
  const [isOpen, setIsOpen] = useState(false);
  const ref = useRef();

  useOnClickOutside(ref, () => setIsOpen(false));

  return (
    <div ref={ref}>
      <button onClick={() => setIsOpen(!isOpen)}>Menu</button>
      {isOpen && <div>Menu content</div>}
    </div>
  );
}

Rules for Custom Hooks

Benefits of Custom Hooks

✨ Advantages:
  • Reusability: Use the same logic in multiple components
  • Separation of Concerns: Keep logic separate from UI
  • Testability: Easier to test hooks in isolation
  • Readability: Components become cleaner and more focused
  • Maintainability: Update logic in one place

When to Create a Custom Hook

💡 Create a custom hook when:
  • You're using the same stateful logic in multiple components
  • The logic is complex and clutters your component
  • You want to share logic without HOCs or render props
  • You need to compose multiple hooks together

Custom Hook Best Practices

1. Return Values Clearly

// ✅ Good - clear what's returned
return { data, isLoading, error, refetch };

// ✅ Also good - array for simple returns
return [value, setValue];

2. Handle Cleanup

function useEventListener(event, handler) {
  useEffect(() => {
    window.addEventListener(event, handler);
    
    // ✅ Always cleanup
    return () => {
      window.removeEventListener(event, handler);
    };
  }, [event, handler]);
}

3. Use Descriptive Names

// ✅ Good names
useFetch
useLocalStorage
useAuth
useWindowSize

// ❌ Bad names
useData
useHelper
useLogic

4. Keep Them Focused

// ✅ Good - does one thing
function useFetch(url) { /* ... */ }

// ❌ Bad - does too many things
function useEverything() {
  // fetching, auth, theme, routing...
}

Popular Custom Hooks Libraries

Complete Example

Here's a complete example showing how custom hooks simplify components:

Before (without custom hook)

function UserProfile() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('/api/user')
      .then(res => res.json())
      .then(data => {
        setUser(data);
        setLoading(false);
      })
      .catch(err => {
        setError(err);
        setLoading(false);
      });
  }, []);

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

After (with custom hook)

function UserProfile() {
  const { data: user, loading, error } = useFetch('/api/user');

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
  return <div>{user.name}</div>;
}
🎉 Much Cleaner! The component is now focused on rendering, while the hook handles the data fetching logic.

Congratulations! 🎉

You've completed the React tutorial! You now know:

📚 Keep Learning:
  • Build real projects to practice
  • Explore advanced patterns
  • Learn state management (Redux, Zustand)
  • Study Next.js for server-side rendering
  • Contribute to open source

Next Steps

Now that you've mastered React, start building your own projects! The best way to learn is by doing.