React Hooks Custom Hooks 2 — Questions and Answers
Question 1: Which built-in hook pair is most commonly combined in a useFetch custom hook?
- useMemo and useCallback
- useState and useEffect (Correct answer)
- useRef and useContext
- useReducer and useLayoutEffect
Correct answer: useState and useEffect
A useFetch hook typically uses useState to store data/loading/error and useEffect to trigger the fetch.
Question 2: How should a custom hook expose a way to update shared logic state to its consuming component?
- By modifying a global variable
- By returning a setter or action function from the hook (Correct answer)
- By using a class property
- By dispatching a window event
Correct answer: By returning a setter or action function from the hook
Returning a setter or action function from the custom hook lets the consumer trigger state changes cleanly.
Question 3: What is a useLocalStorage custom hook typically used for?
- Caching API responses in memory
- Persisting state to localStorage and syncing it with component state (Correct answer)
- Encrypting data before storage
- Managing cookies
Correct answer: Persisting state to localStorage and syncing it with component state
useLocalStorage wraps useState with read/write logic for localStorage, keeping them in sync.
Question 4: Can a custom hook call another custom hook?
- No, only built-in hooks can be composed
- Yes, hooks can call other hooks freely (Correct answer)
- Only if they share the same dependency array
- Only in the same file
Correct answer: Yes, hooks can call other hooks freely
Custom hooks are just functions, so they can freely call other custom or built-in hooks.
Question 5: Why is it important to clean up side effects in custom hooks?
- React requires it for TypeScript compatibility
- To prevent memory leaks and stale subscriptions when components unmount (Correct answer)
- To satisfy the exhaustive-deps lint rule
- To improve initial render time
Correct answer: To prevent memory leaks and stale subscriptions when components unmount
If a custom hook sets up a subscription or interval, failing to clean it up causes memory leaks after the component unmounts.
Question 6: What testing strategy works best for isolated custom hooks?
- Render the full app and check side effects
- Use @testing-library/react-hooks or renderHook to test the hook in isolation (Correct answer)
- Only test via E2E tests
- Mock all state with jest.fn()
Correct answer: Use @testing-library/react-hooks or renderHook to test the hook in isolation
renderHook from React Testing Library renders a minimal wrapper so you can test the hook's behavior in isolation.
Which built-in hook pair is most commonly combined in a useFetch custom hook?