React allows calling a custom hook inside another custom hook. This approach is ideal for composing logic cleanly, just follow the Rules of Hooks.
Example: Composing Custom Hooks
Suppose you have two custom hooks:
A simple custom hook for toggling a boolean state
js
// useToggle.jsimport { useState } from ‘react’;
export function useToggle(initial = false) {
const [value, setValue] = useState(initial);
const toggle = () => setValue(v => !v);
return [value, toggle];
}
A custom hook that uses useToggle and adds extra logic
// useDropdown.jsimport { useToggle } from ‘./useToggle’;
export function useDropdown() {
const [isOpen, toggleOpen] = useToggle(false);
// You can add more logic here if needed
function open() { if (!isOpen) toggleOpen(); }
function close() { if (isOpen) toggleOpen(); }
return { isOpen, open, close, toggle: toggleOpen };
}
Also Read: The SEO for React Websites
Using the composed hook in a component
import { useDropdown } from ‘./useDropdown’;
function DropdownMenu() {
const { isOpen, open, close, toggle } = useDropdown();
return (
<div>
<button onClick={toggle}>Toggle Menu</button>
{isOpen && <div>Menu Content</div>}
</div>
);
}
Here, useDropdown calls another custom hook, useToggle, internally.
Key Takeaways
- Yes, you can nest custom hooks. It’s encouraged!
- Follow the Rules of Hooks:
- Call hooks at the top level of your custom hook.
- Never call them conditionally.
- Compose for clarity – small hooks ➜ composed hook ➜ lean component.