Contents of React Interview Questions

Comprehensive collection of React interview questions and answers covering hooks, components, state management, and best practices.

What are custom Hooks and how to create them?

Custom Hooks are JavaScript functions that start with use and can call other Hooks inside them. They let you extract reusable logic from components to keep code clean and DRY (Don't Repeat Yourself).

Why use Custom Hooks?

  • Share logic across multiple components.
  • Avoid duplicate code.
  • Make components smaller and easier to understand.

Example of a simple custom Hook:

import { useState, useEffect } from 'react'; 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; } // Usage in a component function MyComponent() { const width = useWindowWidth(); return <div>Window width: {width}px</div>; }