Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

How do you create custom hooks? Custom hooks कैसे बनाते हैं?

Answer
// Custom hook - reusable logic
function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  
  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  
  return width;
}

// Using custom hook
function Component() {
  const width = useWindowWidth();
  return <p>Width: {width}</p>;
}

// Custom hook for API calls
function useApi(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    fetch(url)
      .then(res => res.json())
      .then(data => {
        setData(data);
        setLoading(false);
      });
  }, [url]);
  
  return { data, loading };
}
Custom hook बनाना:
function useHookName() {
  // Logic here
  return value;
}

Rules:
1. Name 'use' से शुरू होना चाहिए
2. Other hooks को call कर सकते हैं
3. Conditional call न करें

Was this answer clear?