Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 57

Understanding Custom Hooks

Recommended resources

Hello! Welcome to the first lesson of our eighth module, where we'll explore creating reusable logic with custom hooks.

In our last lesson, we optimized React's Context API by memoizing provider values and splitting contexts. One of the advanced patterns we touched on was creating "selector hooks" to consume specific slices of a context's state. This was a perfect practical example of today's topic. You saw how a small, specialized hook could make a component cleaner and more performant. Now, we're going to generalize that idea.

This lesson addresses a foundational concept in modern React development. You'll learn to explain the purpose and benefits of creating custom hooks. This is a key step toward writing professional, clean, and highly maintainable React applications, moving beyond simply using built-in hooks to elegantly composing them.

The Problem: Trapped Logic

As you build more complex applications, you'll often find yourself writing the same stateful logic in multiple components. A component might need to track window size, fetch data from an API, or persist a value to local storage.

Your background in software engineering has likely taught you the importance of the Don't Repeat Yourself (DRY) principle. When you see duplicated logic, your instinct is to extract it into a function. But what happens when that logic involves React hooks like useState or useEffect?

You can't just move it into a regular JavaScript function, because the Rules of Hooks prevent you from calling hooks inside non-component functions. This is where custom hooks come in.

To understand the problems custom hooks solve, let's turn to an article by Dan Abramov, one of the creators of React Hooks.

Making Sense of React Hooks

The article 'Making Sense of React Hooks' explains the original motivation behind hooks. It highlights the challenges of sharing stateful logic in older React patterns and introduces how hooks solve these issues.

Please read the section titled 'Why Hooks?'. Focus on the three problems he lists: huge components, duplicated logic, and complex patterns. This will give you a strong sense of the 'why' behind custom hooks.

As Abramov points out, we often can't break down complex components because the stateful logic is "trapped" inside. Custom hooks are the mechanism for setting that logic free.


What is a Custom Hook? A Mental Model

So, how do you decide when to create a component, a simple utility function, or a custom hook? This simple heuristic is incredibly useful.

Custom Hooks in React - Every React Developer Should Know This

The video 'Custom Hooks in React' from ByteGrad starts by offering a fantastic mental model for reusability in React. This will help you immediately understand the specific role of custom hooks.

Watch the first 28 seconds of the video. The speaker clearly lays out the three main ways to achieve reusability in React. Internalize this distinction.

To summarize the key idea:

  • To reuse UI (JSX): Create a Component.
  • To reuse non-React logic (e.g., sorting an array): Create a Utility Function.
  • To reuse stateful logic (involving hooks like useState or useEffect): Create a Custom Hook.

A custom hook is, fundamentally, a JavaScript function whose name starts with use and that can call other hooks. It allows you to extract component logic into reusable functions.


The Anatomy of a Custom Hook: An Example

Let's make this concrete. The official React documentation provides an excellent walkthrough of extracting a custom hook. We'll follow its example of creating a useOnlineStatus hook.

Reusing Logic with Custom Hooks

This article from the official React documentation, 'Reusing Logic with Custom Hooks', provides a step-by-step guide to identifying duplicated logic and extracting it into a custom hook.

Read the sections 'Custom Hooks: Sharing logic between components' and 'Extracting your own custom Hook from a component'. Notice how the same useState and useEffect logic is present in both the StatusBar and SaveButton components. Then, observe how this logic is moved into a new useOnlineStatus function, cleaning up both components significantly.

As you saw, the process is straightforward:

  1. Identify Duplication: Find two or more components that use the same hooks to manage the same kind of stateful logic.
  2. Extract: Copy the duplicated logic (the useState and useEffect calls) into a new function.
  3. Name It: Name the function starting with use (e.g., useOnlineStatus).
  4. Define the Interface: Determine what arguments the hook needs (if any) and what it should return. In the useOnlineStatus example, it takes no arguments and returns the isOnline boolean.
  5. Replace: Replace the old logic in the components with a single call to your new custom hook.

The Core Benefits of Custom Hooks

Now that you understand what custom hooks are and how to create a simple one, let's systematically explore the benefits they provide.

1. Reusability and Abstraction

This is the most direct benefit. You can write complex, stateful logic once and reuse it across your entire application. This is particularly powerful for abstracting away browser APIs or other external systems.

Let's look at another common and practical example: persisting state to local storage.

Custom Hooks in React - Every React Developer Should Know This

The same ByteGrad video provides an excellent demonstration of creating a useLocalStorage hook. This is a perfect example of abstracting away a browser API.

Watch from 10:37 to 19:56. Pay close attention to: The initial problem: duplicated useState and useEffect logic for managing local storage in two different places. How this logic is extracted into a generic useLocalStorage hook. How the final components are much cleaner and simply call useLocalStorage('theme') or useLocalStorage('items').

2. Separation of Concerns and Readability

Custom hooks allow you to separate UI from logic. Your components become cleaner, more declarative, and easier to read because they describe their intent, not their implementation.

Instead of this:

const [isOnline, setIsOnline] = useState(true);
useEffect(() => {
  // ... logic to handle online/offline events
}, []);

You have this:

const isOnline = useOnlineStatus();

The component doesn't need to know how the online status is determined; it just needs to use it. This separation makes your codebase much easier to reason about and maintain.

3. Improved Testability

Since a custom hook is a standard JavaScript function, you can test its logic in isolation, without needing to render a component. This is a significant advantage that aligns with software engineering best practices. You can write unit tests for your state transitions, side effects, and data manipulations independently of any UI rendering.

No BS TS #23 - Typescript/React - Custom Hooks

In this video by Jack Herrington, he refactors a useReducer into a custom useTodos hook. He explicitly points out the testing benefit at the end.

Watch from 1:19 to 4:56 to see the refactoring, and then from 7:23 to 8:10 for the summary of benefits. Notice his emphasis on how the UI is separated from the logic and how the useTodos hook can be easily unit tested.

4. Independent, Isolated State

This is a critical concept to grasp: custom hooks share stateful logic, not state itself.

Every time you call a custom hook inside a component, it gets its own independent, isolated state. If two different components both call useCounter(), they will each have their own separate count state. They do not share a single count.

Reusing Logic with Custom Hooks

The React docs explain this distinction beautifully with another example.

Read the section 'Custom Hooks let you share stateful logic, not state itself'. The useFormInput example is key here. Note how calling it twice in the Form component is equivalent to declaring two separate useState variables.

This ensures that hooks maintain the predictable, top-down data flow that is central to React's design, while still giving you the power of reusable logic.


Conventions and Rules

To make all of this work, React relies on a few important conventions.

  1. Naming: Custom hook names must start with use. This is not just a convention; it's a rule that allows React's linter to identify hooks and enforce the Rules of Hooks. A function named getOnlineStatus cannot call useState, but useOnlineStatus can.

  2. Rules of Hooks: Because custom hooks are made of other hooks, they must also follow the same rules:

    • Only call hooks at the top level of your component or custom hook.
    • Don't call hooks inside loops, conditions, or nested functions.

The article "Reusing Logic with Custom Hooks" (LINK) has an excellent deep-dive section titled "Hook names always start with use" that is worth reviewing if you are ever unsure about this convention.

This visual provides a great summary of what we've discussed.

Mastering React Custom Hooks: Efficient Development
This diagram shows how a custom hook can centralize functionalities like API calls, theme handling, and form logic. By doing so, it promotes code that is reusable and maintainable, leading to smarter, more efficient development.

Conclusion

You now have a solid understanding of the purpose and benefits of custom hooks in React. They are not just a nice-to-have feature; they are the primary, idiomatic way to share stateful logic, leading to a more modular, testable, and maintainable codebase.

Key Takeaways:

  • Purpose: Custom hooks exist to extract and reuse stateful logic (any logic that uses React hooks like useState or useEffect).
  • Benefits: They improve reusability, enhance readability by separating concerns, enable isolated testability, and provide an elegant abstraction over complex logic.
  • Core Principle: Custom hooks share logic, but not state. Each call to a hook creates an independent state instance for the calling component.
  • Conventions: They must be named with a use prefix and must obey the Rules of Hooks.

Preview of the Next Lesson:
In our next lesson, we'll put this theory into practice. You will learn how to create a generic custom hook with TypeScript, focusing on how to properly type its arguments and return values to create a flexible and type-safe abstraction that can be used throughout an application.