React Hooks Custom Hooks 1 — Questions and Answers
Question 1: What naming convention must all custom hooks follow?
- They must end with 'Hook'
- They must start with 'use' (Correct answer)
- They must start with 'get'
- They must be named after the component
Correct answer: They must start with 'use'
Custom hooks must start with 'use' so React's linter can enforce the Rules of Hooks for them.
Question 2: What is the main benefit of extracting logic into a custom hook?
- Improved rendering speed
- Reusing stateful logic across multiple components without duplicating code (Correct answer)
- Reducing bundle size
- Bypassing React's re-render cycle
Correct answer: Reusing stateful logic across multiple components without duplicating code
Custom hooks let you extract and share stateful logic (state, effects, subscriptions) across components cleanly.
Question 3: Can two components using the same custom hook share state?
- Yes, state is shared between all components using the same hook
- No, each component gets its own isolated state instance (Correct answer)
- Only if the hook uses useContext
- Yes, if the hook uses useRef
Correct answer: No, each component gets its own isolated state instance
Each component that calls a custom hook gets its own isolated copy of the hook's state and effects.
Question 4: Which of the following can a custom hook contain?
- Only useState calls
- Only useEffect calls
- Any combination of built-in hooks and logic (Correct answer)
- JSX markup
Correct answer: Any combination of built-in hooks and logic
A custom hook is just a JavaScript function that can call any built-in or custom hooks internally.
Question 5: Where can a custom hook be called from?
- Only inside class components
- Only inside useEffect
- Inside function components or other custom hooks (Correct answer)
- Inside event handlers
Correct answer: Inside function components or other custom hooks
Hooks (including custom ones) can only be called at the top level of function components or other hooks.
Question 6: What does a custom hook typically return?
- It must return JSX
- It must return a single value
- It can return anything: values, functions, arrays, objects, or nothing (Correct answer)
- It must return a [state, setState] tuple
Correct answer: It can return anything: values, functions, arrays, objects, or nothing
Custom hooks have no restrictions on their return value; they can return whatever their consumers need.
What naming convention must all custom hooks follow?