React Hooks 1 — Questions and Answers
Question 1: What is useState in React?
- A CSS property
- A hook that adds state to functional components, returning the current value and a function to update it (Correct answer)
- A routing function
- A testing utility
Correct answer: A hook that adds state to functional components, returning the current value and a function to update it
useState returns a pair: the current state value and a setter function. When the setter is called, the component re-renders with the new value.
Question 2: What is useEffect used for?
- Adding visual effects
- Performing side effects like data fetching, subscriptions, or DOM manipulation after render (Correct answer)
- Creating animations only
- Error handling
Correct answer: Performing side effects like data fetching, subscriptions, or DOM manipulation after render
useEffect runs after render and handles side effects. The dependency array controls when it re-runs. Cleanup functions handle teardown.
Question 3: What is the dependency array in useEffect?
- A list of npm packages
- An array of values that determines when the effect should re-run — changes trigger re-execution (Correct answer)
- A required parameter
- An error array
Correct answer: An array of values that determines when the effect should re-run — changes trigger re-execution
The dependency array tells React which values to watch. Empty array = run once. No array = run every render. With values = run when those values change.
Question 4: What is useContext?
- A debugging tool
- A hook that accesses context values without wrapping components in Consumer, enabling shared state across the component tree (Correct answer)
- A state manager
- A routing hook
Correct answer: A hook that accesses context values without wrapping components in Consumer, enabling shared state across the component tree
useContext provides a way to pass data through the component tree without prop drilling, accessing values from the nearest matching Context Provider.
Question 5: What is useRef used for?
- Creating references to other files
- Creating a mutable reference that persists across renders without causing re-renders when changed (Correct answer)
- A type of state
- A routing parameter
Correct answer: Creating a mutable reference that persists across renders without causing re-renders when changed
useRef creates a container for a mutable value that persists across renders. Common uses include accessing DOM elements and storing previous values.
Question 6: What is useMemo?
- A note-taking hook
- A hook that memoizes expensive calculations, only recomputing when dependencies change (Correct answer)
- A memory management tool
- A memo component
Correct answer: A hook that memoizes expensive calculations, only recomputing when dependencies change
useMemo caches the result of an expensive computation and only recalculates when its dependencies change, preventing unnecessary recalculations on every render.
What is useState in React?