QA
Beginner LevelReact JS & React 19

What is a Custom Hook and what rules must custom hooks follow?

❓ Interview Prompt: Explain Custom Hooks, abstracting stateful logic, `use` prefix convention, and Rules of Hooks.

A Custom Hook is a JavaScript function whose name starts with 'use' and that may call other React hooks:

Why Custom Hooks?

Allows extracting and sharing stateful logic (fetching data, tracking window resize, handling form inputs) across multiple components without duplicating code!

Rules of Hooks:

1
Call hooks ONLY at the top level: Do not call hooks inside loops, conditions, or nested functions (except React 19 'use()'!).
2
Call hooks ONLY from React function components or custom hooks.

Code Implementation Example

jsx
// Custom Hook extracting window width tracking logic
function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return width;
}

// Usage in component:
function ResponsiveHeader() {
  const width = useWindowWidth(); // Reusable hook call!
  return <h2>Window width: {width}px</h2>;
}
💡Extracting window resize tracking into a reusable custom hook.
🎯 Interview Key Takeaway

Custom hooks start with 'use' and allow sharing stateful logic across components while following the Rules of Hooks.

#Custom Hooks#Hooks#Reusability#Beginner
Back to all React JS & React 19 Questions→

More React JS & React 19 Interview Questions

Beginner LevelReact JS & React 19

What is JSX and how does it work under the hood?

Beginner LevelReact JS & React 19

What is the difference between props and state in React?

Beginner LevelReact JS & React 19

How does the useState hook work and what is functional updater syntax?