Skip to main content
TOPIC 4 OF 6 · 2 MIN READ

Custom Hooks in React

A custom hook is a JavaScript function that utilizes one or more React hooks (`useState`, `useEffect`, etc.) to encapsulate reusable logic. Custom hooks enable code reusability and modularity.

Key concepts

Custom Hook

A JavaScript function that utilizes one or more React hooks to encapsulate reusable logic. Custom hooks start with the prefix `use` (e.g., `useFetch`, `useToggle`).

Step by step

How to Create a Custom Hook:

  • Custom hooks start with the prefix `use` (e.g., `useFetch`, `useToggle`).
  • Encapsulate the logic you want to reuse.
  • Return state, methods, or values for use in components.

Benefits of Custom Hooks:

  • Reusability: Encapsulate logic and use it across multiple components.
  • Readability: Reduces clutter in components by abstracting logic.
  • Testability: Makes logic easier to isolate and test.

Examples

useFetch Custom Hook:

import { useState, useEffect } from 'react';

function useFetch(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 component
function App() {
  const { data, loading } = useFetch('https://jsonplaceholder.typicode.com/posts');

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

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

useToggle Custom Hook:

function useToggle(initialValue = false) {
  const [state, setState] = useState(initialValue);

  const toggle = () => setState((prev) => !prev);

  return [state, toggle];
}

// Usage in a component
function ToggleComponent() {
  const [isVisible, toggleVisibility] = useToggle();

  return (
    <div>
      <button onClick={toggleVisibility}>{isVisible ? 'Hide' : 'Show'}</button>
      {isVisible && <p>Toggle Me!</p>}
    </div>
  );
}

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus