What are Custom Hooks in React
This article provides a comprehensive guide to understanding and using Custom Hooks in React. You will learn what Custom Hooks are, why they are beneficial for developers, the key rules you must follow when creating them, and a practical code example of how to build and implement your own Custom Hook to simplify your codebase.
What is a Custom Hook?
In React, a Custom Hook is a JavaScript function whose name starts
with “use” and that can call other React Hooks (such as
useState, useEffect, and
useContext).
Custom Hooks are a mechanism to reuse stateful logic between components. When you have component logic that needs to be used by multiple components, you can extract that logic into a Custom Hook instead of rewriting it or relying on complex patterns like Render Props or Higher-Order Components.
Why Use Custom Hooks?
Custom Hooks offer several advantages for managing React application logic:
- Code Reusability: You can write logic once and share it across multiple components without duplicating code.
- Separation of Concerns: By extracting complex state logic or side effects from your UI components, you keep your components clean, readable, and focused solely on rendering the user interface.
- Maintainability: If you need to update the shared logic, you only have to modify it in one place (inside the Custom Hook) rather than hunting down every component that uses it.
- Testability: Isolating logic into a separate function makes it much easier to write unit tests for that specific functionality.
Rules for Creating Custom Hooks
To ensure React handles your Custom Hooks correctly, you must follow two strict rules:
- The Name Must Start with “use”: Your function name
must begin with “use” (for example,
useFetchoruseAuth). This naming convention tells React that this function may contain calls to other hooks, enabling React’s linter to automatically check for Hook violations. - Follow the Rules of Hooks: You must only call Hooks at the top level of your Custom Hook. Do not call Hooks inside loops, conditions, or nested functions.
A Practical Example: Creating a Custom Hook
Let’s look at a common scenario: toggling a boolean state (like
opening and closing a modal or sidebar). Instead of writing the same
useState and toggle logic in every component, we can create
a Custom Hook called useToggle.
Step 1: Define the Custom Hook
import { useState } from 'react';
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = () => {
setValue((prevValue) => !prevValue);
};
// Return the state value and the function to update it
return [value, toggle];
}
export default useToggle;Step 2: Use the Custom Hook in a Component
Now, you can import and use the useToggle hook in any
component that needs toggling functionality.
import React from 'react';
import useToggle from './useToggle';
function ToggleComponent() {
const [isModalOpen, toggleModal] = useToggle(false);
const [isDarkMode, toggleDarkMode] = useToggle(false);
return (
<div>
{/* Modal Example */}
<button onClick={toggleModal}>
{isModalOpen ? 'Close Modal' : 'Open Modal'}
</button>
{isModalOpen && <div className="modal">This is a modal window!</div>}
<hr />
{/* Dark Mode Example */}
<button onClick={toggleDarkMode}>
Switch to {isDarkMode ? 'Light' : 'Dark'} Mode
</button>
</div>
);
}
export default ToggleComponent;In this example, both the modal and the dark mode toggle utilize the
exact same stateful logic from useToggle without any code
duplication. Each call to a Custom Hook gets a completely isolated
state, meaning that toggling the modal has no effect on the dark mode
state.