![]() |
VOOZH | about |
A custom hook is a JavaScript function that starts with use and internally calls other hooks like useState, useEffect, or useContext. It allows developers to extract reusable logic, keeping components clean and modular.
Syntax
function useCustomHook() {
// Use built-in hooks here
return someValue;
}
Custom hooks must follow React's naming convention and start with use (e.g., useFetch). This ensures React recognizes it as a hook and enforces hook rules.
function useCustomHook() {
// Hook logic here
return someValue;
}
Custom hooks can use useState, useEffect, useContext, etc., to manage state, handle side effects, or access context.
function useCounter() {
const [count, setCount] = useState(0);
return [count, () => setCount(count + 1)];
}
If your custom hook performs side effects (e.g., fetching data, subscribing to a service), use useEffect to control when the effect runs.
function useFetchData(url) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url).then(response => response.json()).then(setData);
}, [url]);
return data;
}
Your custom hook should return state, functions, or values that components need, such as fetched data, loading state, or error messages.
function useToggle(initialValue = false) {
const [state, setState] = useState(initialValue);
const toggle = () => setState(prev => !prev);
return [state, toggle];
}
Once defined, your custom hook can be used inside a React component just like a built-in hook.
function ExampleComponent() {
const [isOn, toggle] = useToggle();
return <button onClick={toggle}>{isOn ? "ON" : "OFF"}</button>;
}
Custom hooks can be used for handling the API requests.
Output
In this example
This example consists of a custom hook (useOnlineStatus) that tracks the online/offline status of a user and a React component (SaveButton) that uses this custom hook to enable or disable a button based on the network status.
Output
In this example
You should use custom hooks when