React Hooks Building React App 3 — Questions and Answers
Question 1: When building a form, which hook tracks the input field's current value?
- useMemo
- useState (Correct answer)
- useReducer for single fields only
- useCallback
Correct answer: useState
useState is the standard hook for controlled input values.
Question 2: How do you make an input a controlled component in React?
- Set value and onChange props (Correct answer)
- Use only defaultValue
- Add a ref alone
- Use document.getElementById
Correct answer: Set value and onChange props
Binding value to state and updating it via onChange creates a controlled input.
Question 3: Which hook is best for fetching data when the App component first mounts?
- useState
- useEffect with an empty dependency array (Correct answer)
- useRef
- useContext
Correct answer: useEffect with an empty dependency array
useEffect with [] runs once after the initial mount, ideal for fetching data.
Question 4: What should a data-fetching useEffect return to avoid memory leaks?
- A new component
- A cleanup function (Correct answer)
- The fetched data
- A boolean
Correct answer: A cleanup function
Returning a cleanup function lets you cancel requests or clear timers on unmount.
Question 5: To display a list of items from state, which approach is used in JSX?
- A for loop directly in JSX
- Array.map returning elements with keys (Correct answer)
- while loop inline
- forEach returning JSX
Correct answer: Array.map returning elements with keys
Array.map returns an element per item, each needing a unique key prop.
Question 6: Why must list items rendered with map include a key prop?
- For CSS styling
- To help React identify changed items efficiently (Correct answer)
- To set the index
- It is optional and unused
Correct answer: To help React identify changed items efficiently
Keys let React's reconciler track which items changed, added, or removed.
Question 7: When lifting state up, where should shared state live?
- In the closest common parent component (Correct answer)
- In each child separately
- In a CSS file
- In the index.html
Correct answer: In the closest common parent component
State shared by siblings should be lifted to their nearest common ancestor.
When building a form, which hook tracks the input field's current value?