Your Logic, Your Rules: Creating Custom Hooks in React

Extract your component logic into reusable functions to build cleaner, more scalable React applications.

📄

Welcome! Let's see how to make our code much cleaner. This component fetches user data...

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

  useEffect(() => { /* fetch logic here */ }, []);

  if (loading) return <p>Loading...</p>;
  return <h1>{user.name}</h1>;
}

What is a Custom Hook? Logic Encapsulation

A Custom Hook is a JavaScript function whose name starts with `use` and that can call other Hooks (like `useState` or `useEffect`). It lets you "bundle up" related logic into a single, reusable unit, hiding the complex implementation details.

Why Use Them? The DRY Principle

The primary motivation for custom hooks is the DRY principle (Don't Repeat Yourself). If you find yourself writing the same stateful logic in multiple components (like fetching data or managing a form input), it's a perfect candidate to be extracted into a custom hook.

Building a Custom Hook: State and Returns

To build a custom hook, you create a function named `useSomething`. Inside, you can use standard hooks to manage state and side effects. Instead of rendering JSX, you return the state values and updater functions that a component will need to use your logic.

The Result: Clean, Declarative Components

By using a custom hook, your components become declarative and easier to read. They simply call the hook to get the functionality they need (e.g., `const data, loading = useFetch(...)`), without being cluttered by the implementation details. This leads to cleaner, more maintainable code.

Practice Zone


Interactive Test 1: Match the Hook

Match the custom hook to its description.

Arrastra en el orden correspondiente.


Arrastra las opciones:

useToggle
useLocalStorage
useFetch

Completa el código:

Fetches data from an API______
Toggles a boolean value______
Syncs state with localStorage______
Unlock with Premium

Interactive Test 2: Build a Hook

Rellena los huecos en cada casilla.

function (initialValue = 0) {
  const [count, setCount] = (initialValue);

  const increment = () => setCount(c => c + 1);
  const decrement = () => setCount(c => c - 1);

   { count, increment, decrement };
}
Unlock with Premium

Practice Example: Code Editor

Create a custom hook called `useDocumentTitle` that takes an initial title and updates the `document.title` whenever the title changes.

Enunciado:

This hook uses useState to store the title and useEffect to update the document title whenever the state changes.

* Escribe el código a continuación. Los caracteres correctos se mostrarán en verde y los incorrectos en rojo.

import { useState, useEffect } from 'react'; function useDocumentTitle(initialTitle) { const [title, setTitle] = useState(initialTitle); useEffect(() => { document.title = title; }, [title]); return [title, setTitle]; }

Unlock with Premium

Knowledge Check

Which of the following is a fundamental rule of Hooks?


Unlock with Premium

Custom Hooks in Practice

Custom hooks are the building blocks of a scalable React application. Here are a few common patterns you'll see and build in the real world.


1. Abstracting Form Logic: `useInputState`

Managing the state for every single form input can be repetitive. A custom hook can simplify this by handling the value and `onChange` logic for you.

// Usage in component:
const nameInput = useInputState('');

return <input {...nameInput} />

2. Interacting with Browser APIs: `useWindowSize`

Need to render components differently based on screen size? A hook can encapsulate the `resize` event listener logic, including the crucial cleanup step.

const { width, height } = useWindowSize();

return (
 <p>Window size: {width} x {height}</p>
);
Window size: 1024 x 768

3. Creating Complex Interactions: `useDebounce`

For features like a search bar that queries an API, you don't want to send a request on every keystroke. A `useDebounce` hook can delay an effect until the user has stopped typing.

const debouncedSearch = useDebounce(searchTerm, 500);

useEffect(() => {
  // API call fires only after 500ms of inactivity
}, [debouncedSearch]);
API call is waiting...

Practical Takeaway: Custom Hooks transform your mindset. Instead of thinking "How do I build this feature *in this component*?", you start thinking "How do I build this *reusable capability* for my entire app?".

Custom Hooks Glossary

Custom Hook
A JavaScript function whose name starts with "use" and that calls other Hooks. It allows you to extract and reuse stateful logic from a component.
Logic Encapsulation
The practice of bundling related state, effects, and update logic into a single unit (the custom hook), hiding the implementation complexity from the components.
DRY (Don't Repeat Yourself)
A principle of software development aimed at reducing code duplication. Custom hooks are React's primary tool for adhering to the DRY principle.
Rules of Hooks
The two core rules: 1. Only call Hooks at the top level of a React function or another custom hook. 2. Do not call Hooks inside loops, conditions, or nested functions.
Stateful Logic
Any piece of logic that involves managing state (e.g., using `useState`) or side effects (e.g., using `useEffect`). This is the type of logic that custom hooks are designed to share.