React Hooks Javascript 3 — Questions and Answers
Question 1: What does useMemo do?
- Memoizes a computed value to avoid recalculating on every render (Correct answer)
- Stores component state
- Performs side effects
- Creates a context provider
Correct answer: Memoizes a computed value to avoid recalculating on every render
useMemo caches an expensive computed value, recomputing only when dependencies change.
Question 2: What does useCallback return?
- A memoized value
- A memoized version of the callback function (Correct answer)
- A ref object
- A state setter
Correct answer: A memoized version of the callback function
useCallback returns a memoized callback that only changes when dependencies change.
Question 3: Which hook subscribes a component to a React context value?
- useProvider
- useContext (Correct answer)
- useState
- useRef
Correct answer: useContext
useContext reads the current value of a context within a component.
Question 4: What happens if you omit the dependency array entirely in useEffect?
- It runs only once
- It runs after every render (Correct answer)
- It never runs
- It throws an error
Correct answer: It runs after every render
Without a dependency array, the effect runs after every render.
Question 5: Why might updating state inside useEffect without dependencies cause an infinite loop?
- State updates are disabled in effects
- Each state update re-renders, which re-runs the effect, updating state again (Correct answer)
- Effects cannot read state
- React blocks repeated renders
Correct answer: Each state update re-renders, which re-runs the effect, updating state again
The render-update-render cycle repeats endlessly without proper dependencies.
Question 6: What is a custom hook?
- A built-in React API
- A JavaScript function whose name starts with 'use' that calls other hooks (Correct answer)
- A class method
- A CSS utility
Correct answer: A JavaScript function whose name starts with 'use' that calls other hooks
Custom hooks are reusable functions prefixed with 'use' that compose built-in hooks.
Question 7: Which hook would you use to keep a value across renders without triggering a re-render when it changes?
- useState
- useRef (Correct answer)
- useEffect
- useMemo
Correct answer: useRef
useRef stores mutable values that persist but do not cause re-renders on change.