Passing Parameters to Custom Hooks
You'll learn how to make custom hooks flexible by accepting arguments like URLs, initial values, or configuration objects.
The Core Idea
Just like regular functions, custom hooks can accept parameters to make them reusable across different scenarios. Instead of hard-coding values inside your hook, you pass them in as arguments. This transforms a single-purpose hook into a flexible tool you can use throughout your application.
Think of it like a coffee machine: instead of only making one type of coffee, you pass in parameters (beans, size, milk preference) to get exactly what you need each time.
Making Hooks Accept Arguments
When you extracted fetch logic into a custom hook, you might have hard-coded a specific URL. But what if you need to fetch from different endpoints?
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(setData)
.finally(() => setLoading(false));
}, [url]);
return { data, loading };
}
Now you can reuse this hook anywhere:
const { data: users } = useFetch('/api/users');
const { data: posts } = useFetch('/api/posts');
Your useToggle hook could accept an initial value:
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = () => setValue(v => !v);
return [value, toggle];
}
const [isOpen, toggleOpen] = useToggle(true); // starts true
Configuration Objects
For complex hooks, pass a configuration object:
function useFetch({ url, method = 'GET', headers = {} }) {
// use all the parameters
}
Key Takeaway: Parameters transform custom hooks from single-purpose code into flexible, reusable utilities that adapt to different contexts throughout your application.