React Hooks Interview Questions
Comprehensive react hooks interview questions and answers for React JS. Prepare for your next job interview with expert guidance.
Questions Overview
1. What are the Rules of Hooks and why are they important?
Basic2. What's the difference between useMemo and useCallback hooks?
Moderate3. How do you create a custom hook and what are the naming conventions?
Basic4. What is the useRef hook and what are its common use cases?
Moderate5. How does useReducer differ from useState and when should you use it?
Moderate6. What is the purpose of the useImperativeHandle hook?
Advanced7. How do you optimize performance with useMemo and useCallback?
Advanced8. What is the useContext hook and how does it work with React Context?
Moderate9. How do you handle async operations in useEffect?
Moderate10. What is the useLayoutEffect hook and when should it be used instead of useEffect?
Advanced11. How do you implement a custom hook for form handling?
Moderate12. What are the patterns for sharing stateful logic between components using hooks?
Advanced13. How do you handle cleanup in custom hooks?
Moderate14. What is the useDebugValue hook and when should it be used?
Advanced15. How do you implement a hook for managing window events?
Moderate16. What are the common pitfalls when using the dependency array in hooks?
Advanced17. How do you implement pagination logic using hooks?
Moderate18. What is the pattern for implementing debouncing with hooks?
Advanced19. How do you handle error boundaries with hooks?
Advanced20. What is the pattern for implementing undo/redo functionality with hooks?
Advanced21. How do you implement data fetching patterns with hooks?
Moderate22. What are the patterns for managing WebSocket connections with hooks?
Advanced23. How do you implement localStorage persistence with hooks?
Moderate24. What are the patterns for implementing authentication with hooks?
Advanced25. How do you implement infinite scroll with hooks?
Advanced26. What is the pattern for implementing form validation with hooks?
Moderate27. How do you implement theme switching with hooks?
Moderate28. What are the patterns for implementing keyboard shortcuts with hooks?
Advanced29. How do you implement state machine patterns with hooks?
Advanced1. What are the Rules of Hooks and why are they important?
BasicThe Rules of Hooks are: 1) Only call hooks at the top level (not inside loops, conditions, or nested functions), 2) Only call hooks from React function components or custom hooks. These rules ensure hooks maintain their state and order between renders.
2. What's the difference between useMemo and useCallback hooks?
ModerateuseMemo memoizes a computed value and returns it, while useCallback memoizes a function definition. useMemo is used for expensive calculations, while useCallback is used for function props to prevent unnecessary re-renders of child components.
3. How do you create a custom hook and what are the naming conventions?
BasicCustom hooks are functions that use other hooks and must start with 'use' (e.g., useCustomHook). They allow you to extract component logic into reusable functions. Custom hooks can return any values and should follow the Rules of Hooks.
4. What is the useRef hook and what are its common use cases?
ModerateuseRef returns a mutable ref object that persists across renders. Common uses include: accessing DOM elements directly, storing previous values, and holding mutable values that don't trigger re-renders. The .current property can be modified without causing re-renders.
5. How does useReducer differ from useState and when should you use it?
ModerateuseReducer is preferable for complex state logic involving multiple values or when next state depends on previous state. It follows a Redux-like pattern with actions and reducers, making state transitions more predictable and easier to test.
6. What is the purpose of the useImperativeHandle hook?
AdvanceduseImperativeHandle customizes the instance value exposed to parent components when using ref. It allows you to control which values and methods are accessible via the ref, enabling better encapsulation of component internals.
7. How do you optimize performance with useMemo and useCallback?
AdvancedUse useMemo for expensive calculations and useCallback for function props passed to optimized child components. Ensure dependency arrays are properly configured. Only use when there's a measurable performance benefit to avoid unnecessary complexity.
8. What is the useContext hook and how does it work with React Context?
ModerateuseContext subscribes to context changes and returns the current context value. It provides a simpler way to consume context compared to Context.Consumer. Components using useContext will re-render when the context value changes.
9. How do you handle async operations in useEffect?
ModerateDefine an async function inside useEffect and call it, or use IIFE. Handle cleanup properly for ongoing operations. Consider race conditions and component unmounting. Don't make the useEffect callback itself async.
10. What is the useLayoutEffect hook and when should it be used instead of useEffect?
AdvanceduseLayoutEffect fires synchronously after DOM mutations but before browser paint. Use it when you need to make DOM measurements or mutations that should be synchronized with rendering to prevent visual flickers.
11. How do you implement a custom hook for form handling?
ModerateCreate a custom hook that manages form state, validation, submission, and error handling using useState or useReducer. Return form state, handlers, and utility methods. Consider validation timing and form reset functionality.
12. What are the patterns for sharing stateful logic between components using hooks?
AdvancedCreate custom hooks that encapsulate the shared logic, state, and side effects. Ensure hooks are generic enough for reuse but specific enough to be useful. Consider composition of multiple hooks for complex logic.
13. How do you handle cleanup in custom hooks?
ModerateReturn cleanup functions from useEffect within custom hooks. Clear timeouts, cancel subscriptions, and remove event listeners. Ensure all resources are properly cleaned up to prevent memory leaks.
14. What is the useDebugValue hook and when should it be used?
AdvanceduseDebugValue adds a label to custom hooks in React DevTools. Use it to display custom hook values for debugging. Consider using the format function parameter to defer expensive formatting until the hook is inspected.
15. How do you implement a hook for managing window events?
ModerateCreate a custom hook that adds event listeners in useEffect and removes them in cleanup. Consider debouncing or throttling events, and use useCallback for event handlers to maintain referential equality.
16. What are the common pitfalls when using the dependency array in hooks?
AdvancedCommon pitfalls include: missing dependencies leading to stale closures, unnecessary dependencies causing excess renders, object/array dependencies causing infinite loops, and circular dependencies. Use ESLint rules and proper dependency management.
17. How do you implement pagination logic using hooks?
ModerateCreate a custom hook that manages page state, items per page, and total pages using useState. Include methods for page navigation and data fetching. Consider caching results and implementing infinite scroll.
18. What is the pattern for implementing debouncing with hooks?
AdvancedUse useCallback and useRef to create a debounced function that delays execution. Clear previous timeout in cleanup. Consider returning both debounced and immediate execution functions.
19. How do you handle error boundaries with hooks?
AdvancedSince error boundaries must be class components, create a custom hook that works with an error boundary component. Use try-catch in event handlers and effects. Consider implementing retry logic and error logging.
20. What is the pattern for implementing undo/redo functionality with hooks?
AdvancedUse useReducer to manage state history array and current index. Implement actions for undo, redo, and new states. Consider memory usage and limiting history size for large state objects.
21. How do you implement data fetching patterns with hooks?
ModerateCreate custom hooks for data fetching using useState and useEffect. Handle loading, error, and success states. Consider caching, request cancellation, and retry logic. Use libraries like react-query for complex cases.
22. What are the patterns for managing WebSocket connections with hooks?
AdvancedCreate a custom hook that establishes connection in useEffect, handles message events, and cleans up on unmount. Consider reconnection logic, message queuing, and connection status management.
23. How do you implement localStorage persistence with hooks?
ModerateCreate a custom hook that syncs state with localStorage using useEffect. Handle serialization/deserialization, storage events for cross-tab synchronization, and fallbacks for when storage is unavailable.
24. What are the patterns for implementing authentication with hooks?
AdvancedCreate custom hooks for managing auth state, token storage, and user session. Handle login, logout, token refresh, and protected routes. Consider persistent sessions and security implications.
25. How do you implement infinite scroll with hooks?
AdvancedCreate a custom hook that manages scroll position, loading state, and data fetching. Use intersection observer or scroll events. Consider data caching, cleanup, and performance optimization.
26. What is the pattern for implementing form validation with hooks?
ModerateCreate custom hooks for validation logic using useState or useReducer. Handle field-level and form-level validation, async validation, and error messages. Consider validation timing and performance.
27. How do you implement theme switching with hooks?
ModerateCreate a custom hook that manages theme state using useState and useContext. Handle theme persistence, dynamic style application, and system preference detection. Consider performance and SSR implications.
28. What are the patterns for implementing keyboard shortcuts with hooks?
AdvancedCreate a custom hook that manages keyboard event listeners using useEffect. Handle key combinations, prevent default behaviors, and clean up listeners. Consider focus management and accessibility.
29. How do you implement state machine patterns with hooks?
AdvancedUse useReducer with a state machine configuration. Define states, transitions, and actions. Consider using libraries like XState. Handle side effects and state persistence.