Episode 2 — React Frontend Architecture NextJS / 2.3 — State and Rerendering Logic
2.3 — Exercise Questions
60 hands-on practice questions covering all sub-topics of State and Re-rendering Logic.
Navigation: ← 2.3.f — Practical Build · Interview Questions →
Section A: What Is State (Questions 1-10)
Q1. A component displays a user's name. The name comes from a parent component and cannot be changed by this component. Is the name state or props in this component? Explain why.
Q2. You have a let count = 0 variable inside a component. When you click a button that runs count += 1, the UI doesn't update. Explain the two reasons why.
Q3. Identify which of these should be state, derived, or constants in a music player component:
- Current song object
- Is playing (true/false)
- Volume level
- Song duration (from the audio file metadata)
- Current playback position
- Time remaining
- Song title (from props)
- Is muted (volume === 0)
Q4. Two <Counter /> components are rendered side by side. You click the increment button on the first counter 5 times. What value does the second counter show? Why?
Q5. You need to track which tab is selected in a Tab component. You store the full tab object: const [selectedTab, setSelectedTab] = useState(tabs[0]). What's wrong with this approach? What should you store instead?
Q6. A form has fields: firstName, lastName, email, fullName, isEmailValid. Which of these should be state and which should be derived?
Q7. Write the three-question test to determine if something should be state. Apply it to the "scroll position" of a page that you want to track.
Q8. Explain the difference between "state ownership" and "state consumption." Give an example where a parent owns state and a child consumes it.
Q9. A developer stores document.getElementById('myDiv').offsetHeight in state. What problems could this cause? What should they use instead?
Q10. You have an e-commerce app with a product list. The user can filter by category, sort by price, and search by name. What should be state? What should be derived?
Section B: useState Hook (Questions 11-20)
Q11. What does useState return? Write the destructured form and explain each part.
Q12. What is the output of this code when the button is clicked once?
function Component() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
console.log(count);
}
return <button onClick={handleClick}>{count}</button>;
}
Q13. Rewrite the handleClick in Q12 so that clicking the button increments count by 3.
Q14. Explain the difference between useState(expensiveFunction()) and useState(expensiveFunction). When should you use each?
Q15. Write a function that adds an item to the beginning of an array stored in state, without mutating the original array.
Q16. Write a function that updates the email field of a user object stored in state, without mutating the original object.
const [user, setUser] = useState({ name: "Alice", email: "old@test.com", age: 25 });
Q17. You have nested state:
const [data, setData] = useState({
settings: {
theme: { primary: "#000", secondary: "#fff" }
}
});
Write the code to update primary to "#333".
Q18. A developer writes this code. What bug does it have?
const [items, setItems] = useState(["a", "b", "c"]);
function removeFirst() {
items.shift();
setItems(items);
}
Q19. When should you use multiple useState calls vs a single object? Give one scenario where each is preferred.
Q20. Build a controlled input that converts text to uppercase as the user types. Show the full component.
Section C: How React Re-renders (Questions 21-30)
Q21. Name the three things that trigger a component to re-render.
Q22. A parent component re-renders. Its child component receives the same props as before. Does the child re-render? Why or why not?
Q23. What is the difference between a re-render and a re-mount? What happens to state in each case?
Q24. Which phase of React's update cycle can be paused/restarted, and which cannot? Why does this matter for your component code?
Q25. A developer puts fetch('/api/data') directly in the component body (not in useEffect). What goes wrong?
Q26. In React Strict Mode, your component renders twice. Why? Is this a bug? Does it happen in production?
Q27. Draw or describe the flow when a user clicks a button that calls setState:
- What happens in the render phase?
- What happens in the commit phase?
- When does the browser paint?
Q28. You have a list of 1000 items. When one item changes, all 1000 re-render. Name two approaches to prevent the unnecessary 999 re-renders.
Q29. Explain why changing a ref (ref.current = newValue) does NOT cause a re-render.
Q30. A component conditionally renders either <AdminPanel /> or <UserPanel /> based on a boolean. When the boolean changes, does React re-render or re-mount the panel component? Why?
Section D: Batching State Updates (Questions 31-40)
Q31. What is batching? Write a code example showing 3 state updates that result in only 1 re-render.
Q32. In React 16, the following code causes 2 re-renders instead of 1. Why?
setTimeout(() => {
setCount(1);
setName("Alice");
}, 1000);
Does this still happen in React 18?
Q33. What is the final value of count after this handler runs?
const [count, setCount] = useState(0);
function handler() {
setCount(count + 5);
setCount(prev => prev + 1);
setCount(10);
setCount(prev => prev + 1);
}
Q34. Explain what flushSync does. Write a scenario where you'd need it.
Q35. In an async function:
async function handleSubmit() {
setLoading(true);
setError(null);
const data = await fetchData();
setData(data);
setLoading(false);
}
How many re-renders happen? Identify each batch.
Q36. A developer wraps every setState call in flushSync. What performance impact does this have?
Q37. Are these two approaches equivalent in terms of batching?
// Approach A
function handleClick() {
setA(1);
setB(2);
}
// Approach B
function handleClick() {
setA(1);
}
function handleOtherClick() {
setB(2);
}
Q38. You call setCount(0) when count is already 0. Does React re-render? Why or why not?
Q39. Write code demonstrating that setCount(prev => prev + 1) called 5 times in one handler increments count by 5, while setCount(count + 1) called 5 times only increments by 1.
Q40. In React 18, what enables automatic batching everywhere? What API change is required?
Section E: Derived State (Questions 41-50)
Q41. What is derived state? Give 3 examples of values commonly stored in state that should be derived instead.
Q42. Refactor this component to remove unnecessary state:
function UserList() {
const [users, setUsers] = useState([...]);
const [activeUsers, setActiveUsers] = useState([]);
const [activeCount, setActiveCount] = useState(0);
useEffect(() => {
const active = users.filter(u => u.isActive);
setActiveUsers(active);
setActiveCount(active.length);
}, [users]);
return (
<div>
<p>{activeCount} active users</p>
<ul>{activeUsers.map(u => <li key={u.id}>{u.name}</li>)}</ul>
</div>
);
}
Q43. A shopping cart has items in state. The developer also stores totalPrice in state and updates it with useEffect whenever items change. Explain why this is an anti-pattern and how to fix it.
Q44. When should you use useMemo for a derived value instead of computing it as a plain variable?
Q45. Write a component that takes a list of products as props and displays:
- Total number of products
- Number in stock
- Average price
- Most expensive product name
None of these should be state.
Q46. Identify the single source of truth issue:
function Editor() {
const [text, setText] = useState("Hello");
const [charCount, setCharCount] = useState(5);
const [wordCount, setWordCount] = useState(1);
function handleChange(e) {
setText(e.target.value);
setCharCount(e.target.value.length);
setWordCount(e.target.value.split(/\s+/).filter(Boolean).length);
}
}
What's wrong? Rewrite it correctly.
Q47. You have a large dataset (50,000 rows) that needs to be filtered and sorted. The filter and sort criteria change frequently. Should you compute this as a plain variable or use useMemo? Justify your answer.
Q48. A form has password and confirmPassword fields. The developer stores passwordsMatch in state. Rewrite to use a derived value.
Q49. Explain the "extra render" problem that occurs when using useEffect to sync derived state. Draw a timeline showing what happens.
Q50. Given this state structure, identify all the derived values and rewrite:
const [todos, setTodos] = useState([...]);
const [filter, setFilter] = useState("all");
const [filteredTodos, setFilteredTodos] = useState([]);
const [completedCount, setCompletedCount] = useState(0);
const [remainingCount, setRemainingCount] = useState(0);
const [allComplete, setAllComplete] = useState(false);
const [progress, setProgress] = useState(0);
Section F: Practical Application (Questions 51-60)
Q51. Build a component that lets you type a hex color code (e.g., "#3b82f6") and displays a preview box with that color. Track only the text input in state; derive whether the hex code is valid.
Q52. Build a "like counter" component:
- Shows current like count
- Heart button that toggles between liked/not liked
- When liked, count increments; when unliked, count decrements
- Show the heart as filled (red) when liked, outline when not
Identify what's state and what's derived.
Q53. Build a timer that counts up every second when started. Use:
useStatefor the elapsed timeuseReffor the interval ID- Derived values for minutes and seconds display
Explain why the interval ID should be a ref, not state.
Q54. You have a list of students with names and grades. Build a component that:
- Shows the list
- Has a search input to filter by name
- Shows the class average
- Highlights students above average
Identify state vs derived values.
Q55. A developer writes this code for a dark mode toggle. Identify 3 problems:
function App() {
const [isDark, setIsDark] = useState(false);
const [backgroundColor, setBackgroundColor] = useState("#fff");
const [textColor, setTextColor] = useState("#000");
useEffect(() => {
if (isDark) {
setBackgroundColor("#1a1a1a");
setTextColor("#fff");
} else {
setBackgroundColor("#fff");
setTextColor("#000");
}
}, [isDark]);
return (
<div style={{ backgroundColor, color: textColor }}>
<button onClick={() => setIsDark(!isDark)}>Toggle</button>
</div>
);
}
Q56. Build a password strength meter. The input is the password (state). Derive:
- Strength score (0-4)
- Strength label ("Weak", "Fair", "Good", "Strong")
- Color for the meter bar
- List of unmet criteria
Q57. You're building a spreadsheet-like grid. Each cell can be edited. Should you store the entire grid as one piece of state, or each cell as its own useState? What are the tradeoffs?
Q58. Build a BMI calculator:
- Inputs: height (cm) and weight (kg) -- both are state
- Derived: BMI value, BMI category ("Underweight", "Normal", etc.), health tip
Q59. A parent component has a list of items in state. A child component receives one item as a prop and needs to edit it. Design the state architecture: where does state live, how does the child communicate changes back?
Q60. You notice that clicking a button in your app causes 47 components to re-render (visible in React DevTools). Only 3 of them actually display different content. List the steps you'd take to diagnose and fix this, in order. Which tools would you use?
Navigation: ← 2.3.f — Practical Build · Interview Questions →