Chapter 11: Custom Hooks Development
Chapter 11 of 15
Chapter 11: Custom Hooks Development
11.1 Building Reusable Hooks
Custom hooks encapsulate reusable logic, making components cleaner and logic shareable across the application.
// useToggle hook
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => setValue(v => !v), []);
const setTrue = useCallback(() => setValue(true), []);
const setFalse = useCallback(() => setValue(false), []);
return [value, { toggle, setTrue, setFalse }];
}
// Usage
function Component() {
const [isOpen, { toggle, setTrue, setFalse }] = useToggle();
return (
<div>
<button onClick={toggle}>Toggle</button>
{isOpen && <Modal />}
</div>
);
}
11.2 Advanced Hook Patterns
// usePrevious hook
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
// useInterval hook
function useInterval(callback, delay) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
if (delay !== null) {
const id = setInterval(() => {
savedCallback.current();
}, delay);
return () => clearInterval(id);
}
}, [delay]);
}
11.3 Composing Hooks
// Combine multiple hooks
function useUserProfile(userId) {
const { data: user, loading, error } = useFetch(`/api/users/${userId}`);
const [isEditing, toggleEdit] = useToggle(false);
const [notifications, setNotifications] = useLocalStorage('notifications', []);
return {
user,
loading,
error,
isEditing,
toggleEdit,
notifications,
setNotifications
};
}