React Hooks Javascript 2 — Questions and Answers
Question 1: What does the useState hook return?
- An array with the state value and a setter function (Correct answer)
- A single state object
- Only the state value
- A promise that resolves to the state
Correct answer: An array with the state value and a setter function
useState returns a pair: the current state and a function to update it.
Question 2: Which hook lets you perform side effects in a function component?
- useState
- useEffect (Correct answer)
- useMemo
- useRef
Correct answer: useEffect
useEffect handles side effects such as data fetching and subscriptions.
Question 3: When does an effect with an empty dependency array `[]` run?
- After every render
- Only once after the initial mount (Correct answer)
- Never
- Before every render
Correct answer: Only once after the initial mount
An empty dependency array runs the effect only once after the first render.
Question 4: What is the purpose of the cleanup function returned by useEffect?
- To reset all state
- To run before the component unmounts or before re-running the effect (Correct answer)
- To delete the component
- To trigger a re-render
Correct answer: To run before the component unmounts or before re-running the effect
The returned function cleans up subscriptions or timers before unmount or re-run.
Question 5: Which hook returns a mutable object whose `.current` persists across renders without causing re-renders?
- useState
- useRef (Correct answer)
- useReducer
- useContext
Correct answer: useRef
useRef returns a mutable ref object that persists without triggering re-renders.
Question 6: What rule governs where Hooks can be called?
- Only inside loops
- Only at the top level of a component or custom hook (Correct answer)
- Anywhere in the file
- Only inside event handlers
Correct answer: Only at the top level of a component or custom hook
Hooks must be called at the top level, not inside loops, conditions, or nested functions.
Question 7: Which hook is preferred for managing complex state logic with multiple sub-values?
- useReducer (Correct answer)
- useState
- useEffect
- useCallback
Correct answer: useReducer
useReducer suits complex state transitions handled through a reducer function.
What does the useState hook return?