Unit 3: State, Events, Hooks, and Side Effects - Practice Quiz

INT252 — Web App Development With Reactjs 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 Which prop is commonly used to handle a button click in React?

Event handling mechanisms in React Easy
A. onLoad
B. onChange
C. onSubmit
D. onClick

2 How should a function named handleClick normally be assigned as a React click handler?

Event handling mechanisms in React Easy
A. onClick="handleClick"
B. onClick={handleClick}
C. onClick={handleClick()}
D. onClick={return handleClick}

3 What does the useState hook return?

Local state management using useState Easy
A. A state value and setter
B. A context and provider
C. A state value and reducer
D. An effect and cleanup

4 Which code correctly creates a state variable named count with an initial value of 0?

Local state management using useState Easy
A. const [count, setCount] = useState(0);
B. const count = useState.setValue(0);
C. const count = new useState(0);
D. const [count] = useEffect(0);

5 What does React batching do with multiple state updates in the same event handler?

State update behavior and batching Easy
A. Groups them before re-rendering
B. Converts them into props
C. Sends them to the server
D. Cancels all later updates

6 Which update is preferred when the next count depends on its previous value?

State update behavior and batching Easy
A. setCount(count = count + 1)
B. setCount(useEffect(count))
C. count = count + 1
D. setCount(c => c + 1)

7 Which action normally triggers a React component to re-render?

Re-render triggers and optimization awareness Easy
A. Importing a stylesheet
B. Adding a code comment
C. Declaring a constant
D. Updating its state

8 What is derived state?

Derived state concepts Easy
A. A value calculated from existing data
B. A value declared outside React
C. A value created by an event object
D. A value stored only on a server

9 How should an array stored in React state usually be updated?

State management best practices Easy
A. Store it in the DOM
B. Convert it into a string
C. Mutate the existing array
D. Create a new array

10 Which built-in hook reads a value from a React context?

Built-in hooks including useState, useEffect, and useContext Easy
A. useContext
B. useEffect
C. useState
D. useMemo

11 Which task is a typical side effect handled with useEffect?

Managing side effects using useEffect Easy
A. Destructuring component props
B. Returning JSX from a component
C. Declaring a local variable
D. Fetching data from an API

12 When does a useEffect callback normally run?

Managing side effects using useEffect Easy
A. While JSX is compiled
B. After React renders
C. Before the component function
D. Before JavaScript is loaded

13 What happens when useEffect is used without a dependency array?

Dependency array semantics and effect cleanup Easy
A. It never runs automatically
B. It runs only before mounting
C. It runs only after mounting
D. It runs after every render

14 What does [count] mean in useEffect(() => { ... }, [count])?

Dependency array semantics and effect cleanup Easy
A. The effect depends on count
B. The effect deletes count
C. The effect converts count
D. The effect creates count

15 How does an effect provide a cleanup operation?

Dependency array semantics and effect cleanup Easy
A. By throwing an event
B. By exporting a variable
C. By returning a function
D. By returning a JSX element

16 What does useCallback memoize?

Performance optimization using useCallback and useMemo Easy
A. A state setter
B. A JSX attribute
C. A function reference
D. A context provider

17 What does useMemo commonly memoize?

Performance optimization using useCallback and useMemo Easy
A. A component state setter
B. A computed value
C. A browser event
D. A CSS class name

18 What is the main purpose of a custom hook?

Introduction to custom hooks for logic reuse Easy
A. Replace all components
B. Reuse stateful logic
C. Create HTML tags
D. Compile JavaScript files

19 Where should hooks be called in a React function component?

Rules of hooks Easy
A. Inside an event callback
B. Inside any loop
C. Inside any condition
D. At the top level

20 Which action is a common React state anti-pattern?

Common pitfalls and anti-patterns Easy
A. Reading state during render
B. Passing data through props
C. Using a state setter
D. Mutating state directly

21 Which event handler correctly passes an item identifier to a React function component when the button is clicked?

Event handling mechanisms in React Medium
A. onClick={handleDelete(id)}
B. onClick={handleDelete}
C. onClick={() => handleDelete(id)}
D. onClick={function handleDelete(id)}

22 What is the best way to update a counter when the new value depends on the previous value?

Local state management using useState Medium
A. setCount(count + 1)
B. setCount(current => current + 1)
C. setCount(() => count)
D. count = count + 1

23 Given setCount(count + 1); setCount(count + 1); inside one event handler, what usually happens when count is initially 0?

State update behavior and batching Medium
A. The count becomes 0
B. The count becomes 2
C. The component throws an error
D. The count becomes 1

24 Which change normally causes a function component to render again?

Re-render triggers and optimization awareness Medium
A. A constant is declared inside the component
B. A comment is added to the JSX
C. A state setter receives a different value
D. A local variable changes without a setter

25 A component receives price and quantity as props and displays their product. Which approach is generally preferred?

Derived state concepts Medium
A. Update the product only after a button click
B. Compute the product directly during rendering
C. Compute the product inside an empty effect
D. Store the product in state and synchronize it

26 A form has several related fields that must be updated together based on the previous form state. Which approach is most appropriate?

State management best practices Medium
A. Use one state object with functional updates
B. Update the DOM fields directly
C. Use several unrelated mutable variables
D. Store each field in a constant

27 Which hook is most suitable for reading a theme value supplied by a React context?

Built-in hooks including useState, useEffect, and useContext Medium
A. useEffect
B. useState
C. useMemo
D. useContext

28 A component must subscribe to a browser event when it mounts. Which pattern is most appropriate?

Managing side effects using useEffect Medium
A. Call addEventListener in a state initializer
B. Call addEventListener inside JSX
C. Call addEventListener during every render
D. Call addEventListener inside useEffect

29 What does an effect with dependency array [userId] do when userId changes?

Dependency array semantics and effect cleanup Medium
A. It runs after the first render and when userId changes
B. It runs after every render
C. It runs only during the first render
D. It runs only when the component unmounts

30 Which cleanup is needed for an interval created inside an effect?

Dependency array semantics and effect cleanup Medium
A. return setInterval(timerId)
B. return clearInterval(timerId)
C. return () => clearInterval(timerId)
D. return () => setInterval(timerId)

31 When is useMemo most useful in a component?

Performance optimization using useCallback and useMemo Medium
A. When changing a value without rendering
B. When preserving a computed value between renders
C. When running an effect after every render
D. When replacing all event handlers

32 Why might a parent component use useCallback when passing a function to a memoized child?

Performance optimization using useCallback and useMemo Medium
A. To keep the function reference stable
B. To prevent the child from receiving props
C. To convert the function into state
D. To make the function execute immediately

33 What is the main purpose of a custom hook such as useWindowWidth?

Introduction to custom hooks for logic reuse Medium
A. To create reusable stateful logic
B. To render JSX without a component
C. To replace every component prop
D. To define a class component

34 Which example follows the Rules of Hooks?

Rules of hooks Medium
A. Call useEffect inside a loop
B. Call useContext at the component top level
C. Call useState inside an if statement
D. Call useMemo inside a click handler

35 What is a common problem with using an effect to calculate a value that can be computed from props during rendering?

Common pitfalls and anti-patterns Medium
A. It makes the calculation run only once
B. It automatically converts props into context
C. It may cause an unnecessary extra render
D. It always prevents the component from mounting

36 Which code correctly increments a counter three times within one handler?

State update behavior and batching Medium
A. setCount(1); setCount(1); setCount(1)
B. count++; count++; count++
C. setCount(count + 1); setCount(count + 1); setCount(count + 1)
D. setCount(value => value + 1); setCount(value => value + 1); setCount(value => value + 1)

37 A controlled input uses value={name}. Which handler correctly updates its value?

Event handling mechanisms in React Medium
A. onInput={name => setName(name.value)}
B. onChange={event => setName(event.target.value)}
C. onChange={event => name = event.value}
D. onChange={setName(event.target)}

38 A child component receives an inline object prop from its parent on every render. Why can this affect a memoized child?

Re-render triggers and optimization awareness Medium
A. Objects cannot be passed as props
B. React automatically freezes every object
C. The object reference may differ each render
D. Memoized children ignore primitive props

39 Why should state updates avoid directly mutating an existing array?

State management best practices Medium
A. Arrays cannot contain objects in state
B. Mutation always deletes the component
C. Mutation disables event handling
D. React may not detect the same array reference

40 A fetch request starts in an effect and may finish after unmounting. What is an appropriate concern to address?

Managing side effects using useEffect Medium
A. Ignoring or aborting stale requests
B. Moving the request into the return statement
C. Preventing all future component renders
D. Removing every dependency from the effect

41 A button is rendered inside a form using <button onClick={handleSave}>Save</button>. The handleSave function calls an asynchronous API and then updates state. Which change best prevents an unintended form submission while preserving React's event handling?

Event handling mechanisms in React Hard
A. Add event.stopPropagation() inside handleSave
B. Add event.preventDefault() inside handleSave
C. Wrap handleSave in useMemo before passing it
D. Replace onClick with onSubmit on the button

42 Consider const [user, setUser] = useState({ name: "Ava", age: 20 });. Which update correctly changes only age while preserving the other properties?

Local state management using useState Hard
A. setUser(user.age = 21)
B. setUser({ ...user, age: 21 })
C. setUser(() => ({ age: 21 }))
D. setUser({ age: 21 })

43 Inside one React event handler, the component executes setCount(count + 1); setCount(count + 1);. If count is initially 0, what value will normally be rendered after the handler completes?

State update behavior and batching Hard
A. 0, because both updates are ignored
B. undefined, because the state is temporarily cleared
C. 2, because React batches both updates
D. 1, because both updates read the same snapshot

44 A click handler runs setCount(c => c + 1); setCount(c => c + 1);. What is the resulting value if the initial state is 0?

State update behavior and batching Hard
A. 2, because updater functions compose sequentially
B. 1, because only the first updater runs
C. undefined, because functional updates require an effect
D. 0, because updates are batched

45 A parent component re-renders because its local state changed. A memoized child receives a primitive prop whose value is unchanged. Under normal React behavior, what is the most accurate result?

Re-render triggers and optimization awareness Hard
A. The child skips rendering when its props compare equal
B. The child always re-renders because its parent rendered
C. The child re-renders unless the parent uses useCallback
D. The child skips rendering only if its state is also unchanged

46 A component contains const data = { enabled: true }; and passes data to a child wrapped in React.memo. The parent re-renders for unrelated reasons. Why can the child still re-render?

Re-render triggers and optimization awareness Hard
A. Objects are compared by structural equality
B. React.memo ignores object-valued props
C. Memoized children always render twice
D. A new object reference is created each render

47 A component stores items and also stores filteredItems, which is recalculated whenever a search term changes. What is generally the best design when filtering is inexpensive and deterministic?

Derived state concepts Hard
A. Store items and searchTerm, then derive the filtered list during render
B. Store both values and synchronize them with an effect
C. Store only filteredItems and reconstruct the source list
D. Store filteredItems in context to avoid recalculation

48 Which state structure best represents a form with fields email and password when updates may arrive independently?

State management best practices Hard
A. A derived value containing the concatenated form contents
B. One string containing both values separated by a comma
C. Two state variables or one object updated with functional merging
D. One state variable storing the latest changed field only

49 A component reads theme with useContext(ThemeContext) and also calls useState and useEffect. Which statement is correct when the provider value changes?

Built-in hooks including useState, useEffect, and useContext Hard
A. Only components that call useState re-render
B. The effect runs before the context value becomes available
C. Context values can be read only inside event handlers
D. Consumers can re-render when the context value changes

50 A component fetches data in useEffect(() => { fetchData(id); }, [id]). What is the primary reason the fetch belongs in an effect rather than directly in the component body?

Managing side effects using useEffect Hard
A. Effects prevent the component from ever re-rendering
B. Effects make every request execute synchronously
C. Effects separate external synchronization from pure rendering
D. Effects are the only place where promises can be created

51 A search component starts a request whenever query changes. An older request may finish after a newer one. Which approach best prevents stale results from overwriting current results?

Managing side effects using useEffect Hard
A. Ignore the query in the dependency array
B. Memoize the response with useCallback
C. Use a cleanup function with AbortController or an active flag
D. Call the request directly during JSX evaluation

52 What is the semantic difference between useEffect(effect) and useEffect(effect, []) in a component that mounts once and later re-renders?

Dependency array semantics and effect cleanup Hard
A. The first runs before render; the second runs after every render
B. The first runs only when state changes; the second never runs
C. Both run only after the initial render
D. The first runs after every render; the second runs after mount

53 An effect subscribes to a socket using roomId but declares useEffect(() => subscribe(roomId), []). What is the key defect?

Dependency array semantics and effect cleanup Hard
A. The dependency array must contain the cleanup function
B. The subscription can remain tied to the initial room
C. The effect cannot return a cleanup function
D. The effect runs too often during rendering

54 Which cleanup behavior is correct for useEffect(() => { const id = setInterval(tick, 1000); return () => clearInterval(id); }, [])?

Dependency array semantics and effect cleanup Hard
A. Cleanup runs before every interval callback
B. Cleanup runs when the component unmounts
C. Cleanup is skipped because the array is empty
D. Cleanup runs immediately after the effect callback

55 A memoized child receives a callback from its parent. The callback does not need to change unless userId changes. Which implementation most directly supports child memoization?

Performance optimization using useCallback and useMemo Hard
A. Create the callback with useCallback(() => loadUser(userId), [userId])
B. Pass () => loadUser(userId) inline
C. Create the callback with useMemo(() => loadUser(userId), [])
D. Store the callback result in state during render

56 A component computes an expensive sorted list from items and sortOrder. Which use of useMemo is correct?

Performance optimization using useCallback and useMemo Hard
A. useMemo(() => sort(items, sortOrder), [sort])
B. useMemo(() => sort(items, sortOrder), [])
C. useMemo(sort(items, sortOrder), [items, sortOrder])
D. useMemo(() => sort(items, sortOrder), [items, sortOrder])

57 A custom hook useOnlineStatus subscribes to a browser online-status event. Which property is essential for making the hook reusable across multiple components?

Introduction to custom hooks for logic reuse Hard
A. It must encapsulate setup and cleanup while exposing state or actions
B. It must return JSX for each subscribing component
C. It must keep its subscription in module-level mutable state
D. It must call hooks conditionally based on browser status

58 Which component correctly follows the Rules of Hooks when a feature is enabled conditionally?

Rules of hooks Hard
A. Call different hooks in each branch with matching variable names
B. Call useState inside the event handler when needed
C. Call useEffect only inside if (enabled)
D. Call the hook unconditionally and branch inside its effect or logic

59 An effect contains setTotal(price * quantity) and declares [price, quantity, total] as dependencies. What problem can this create?

Common pitfalls and anti-patterns Hard
A. The state update can cause a redundant render cycle
B. The dependency array prevents all state updates
C. The calculation is guaranteed to use stale props
D. The effect cannot access price after the first render

60 A component uses useEffect(() => { document.title = title; }, []), where title is a prop that can change. What is the most accurate correction?

Common pitfalls and anti-patterns Hard
A. Replace the effect with useCallback(title, [])
B. Remove the effect and assign the title during module initialization
C. Move title into a ref and keep the array empty
D. Add title to the dependency array