React Hooks 2 — Questions and Answers
Question 1: What does the useReducer hook return?
- The current state and a dispatch function (Correct answer)
- Only the current state
- A reducer function and an action
- The previous state and the next state
Correct answer: The current state and a dispatch function
useReducer returns an array containing the current state and a dispatch function to trigger state updates.
Question 2: When does the function passed to useEffect run if the dependency array is empty?
- Only once after the initial render (Correct answer)
- After every render
- Before the component mounts
- Only when the component unmounts
Correct answer: Only once after the initial render
An empty dependency array means the effect runs only once after the initial render, similar to componentDidMount.
Question 3: What is the purpose of the useRef hook?
- To persist a mutable value across renders without causing re-renders (Correct answer)
- To trigger re-renders when a value changes
- To memoize expensive computations
- To manage global application state
Correct answer: To persist a mutable value across renders without causing re-renders
useRef returns a mutable ref object whose .current property persists across renders and does not cause re-renders when changed.
Question 4: Which hook would you use to read a context value in a function component?
- useContext (Correct answer)
- useState
- useReducer
- useMemo
Correct answer: useContext
useContext accepts a context object and returns the current context value for that context.
Question 5: What does useMemo return?
- A memoized value recomputed only when dependencies change (Correct answer)
- A memoized callback function
- A ref to a DOM element
- A state and setter pair
Correct answer: A memoized value recomputed only when dependencies change
useMemo returns a memoized value that is recomputed only when one of its dependencies changes.
Question 6: How does useCallback differ from useMemo?
- useCallback memoizes a function while useMemo memoizes a value (Correct answer)
- useCallback memoizes a value while useMemo memoizes a function
- They are identical in behavior
- useCallback only works with class components
Correct answer: useCallback memoizes a function while useMemo memoizes a value
useCallback returns a memoized callback function, whereas useMemo returns a memoized computed value.
Question 7: What happens if you return a function from a useEffect callback?
- It runs as cleanup before the next effect or on unmount (Correct answer)
- It is ignored by React
- It becomes the new render output
- It runs synchronously during render
Correct answer: It runs as cleanup before the next effect or on unmount
The returned function is the cleanup function, executed before the effect runs again or when the component unmounts.
What does the useReducer hook return?