Advanced Hook Patterns in React

From the React Custom Hooks cheat sheet · Custom Hook Fundamentals · verified Jul 2026

Advanced Hook Patterns

Explore advanced patterns including hook composition, factory hooks, and complex state management

jsx
// Hook with cleanup
function useInterval(callback, delay) {
  const savedCallback = useRef();
  
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);
  
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    
    if (delay !== null) {
      const id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

// Hook with dependencies
function useFetch(url, options) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    const abortController = new AbortController();
    
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await fetch(url, {
          ...options,
          signal: abortController.signal
        });
        const result = await response.json();
        setData(result);
      } catch (err) {
        if (err.name !== 'AbortError') {
          setError(err);
        }
      } finally {
        setLoading(false);
      }
    };
    
    fetchData();
    
    return () => abortController.abort();
  }, [url, JSON.stringify(options)]);
  
  return { data, loading, error };
}
⏱️ Use debounce for search inputs and API calls
🔄 Implement cleanup in effects to prevent memory leaks
📱 Use media query hooks for responsive behavior

More React tasks

Back to the full React Custom Hooks cheat sheet