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. onChange
B. onClick
C. onSubmit
D. onLoad

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

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

3 What does the useState hook return?

Local state management using useState Easy
A. A state value and setter
B. A state value and reducer
C. A context and provider
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] = useEffect(0);
B. const count = new useState(0);
C. const count = useState.setValue(0);
D. const [count, setCount] = useState(0);

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

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

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. count = count + 1
C. setCount(useEffect(count))
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. Updating its state
C. Declaring a constant
D. Adding a code comment

8 What is derived state?

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

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

State management best practices Easy
A. Convert it into a string
B. Store it in the DOM
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. useMemo
B. useContext
C. useEffect
D. useState

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

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

12 When does a useEffect callback normally run?

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

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

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

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

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

15 How does an effect provide a cleanup operation?

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

16 What does useCallback memoize?

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

17 What does useMemo commonly memoize?

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

18 What is the main purpose of a custom hook?

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

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

Rules of hooks Easy
A. Inside any loop
B. Inside an event callback
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. Mutating state directly
B. Using a state setter
C. Reading state during render
D. Passing data through props

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(id)}
C. onClick={function handleDelete(id)}
D. onClick={handleDelete}

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(current => current + 1)
B. setCount(count + 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 component throws an error
B. The count becomes 0
C. The count becomes 2
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 local variable changes without a setter
C. A state setter receives a different value
D. A comment is added to the JSX

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

Derived state concepts Medium
A. Compute the product inside an empty effect
B. Update the product only after a button click
C. Compute the product directly during rendering
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. useMemo
C. useContext
D. useState

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 inside JSX
B. Call addEventListener inside useEffect
C. Call addEventListener in a state initializer
D. Call addEventListener during every render

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

Dependency array semantics and effect cleanup Medium
A. It runs only during the first render
B. It runs after the first render and when userId changes
C. It runs after every 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 clearInterval(timerId)
B. return () => setInterval(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 replacing all event handlers
C. When running an effect after every render
D. When preserving a computed value between renders

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 convert the function into state
B. To keep the function reference stable
C. To prevent the child from receiving props
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 replace every component prop
B. To render JSX without a component
C. To define a class component
D. To create reusable stateful logic

34 Which example follows the Rules of Hooks?

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

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 always prevents the component from mounting
C. It may cause an unnecessary extra render
D. It automatically converts props into context

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

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

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

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

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. The object reference may differ each render
B. React automatically freezes every object
C. Objects cannot be passed as props
D. Memoized children ignore primitive props

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

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

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. Wrap handleSave in useMemo before passing it
C. Replace onClick with onSubmit on the button
D. Add event.preventDefault() inside handleSave

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(() => ({ age: 21 }))
C. setUser({ ...user, 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. 2, because React batches both updates
B. undefined, because the state is temporarily cleared
C. 1, because both updates read the same snapshot
D. 0, because both updates are ignored

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. 0, because updates are batched
D. undefined, because functional updates require an effect

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 re-renders unless the parent uses useCallback
B. The child skips rendering only if its state is also unchanged
C. The child always re-renders because its parent rendered
D. The child skips rendering when its props compare equal

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. A new object reference is created each render
B. React.memo ignores object-valued props
C. Objects are compared by structural equality
D. Memoized children always render twice

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 only filteredItems and reconstruct the source list
B. Store both values and synchronize them with an effect
C. Store items and searchTerm, then derive the filtered list during render
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 state variable storing the latest changed field only
C. One string containing both values separated by a comma
D. Two state variables or one object updated with functional merging

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. The effect runs before the context value becomes available
B. Consumers can re-render when the context value changes
C. Only components that call useState re-render
D. Context values can be read only inside event handlers

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 separate external synchronization from pure rendering
C. Effects are the only place where promises can be created
D. Effects make every request execute synchronously

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. Call the request directly during JSX evaluation
B. Memoize the response with useCallback
C. Ignore the query in the dependency array
D. Use a cleanup function with AbortController or an active flag

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. Both run only after the initial render
B. The first runs only when state changes; the second never runs
C. The first runs before render; the second runs after every 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 effect cannot return a cleanup function
B. The dependency array must contain the cleanup function
C. The effect runs too often during rendering
D. The subscription can remain tied to the initial room

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 immediately after the effect callback
B. Cleanup runs before every interval callback
C. Cleanup runs when the component unmounts
D. Cleanup is skipped because the array is empty

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. Create the callback with useMemo(() => loadUser(userId), [])
C. Pass () => loadUser(userId) inline
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), [items, sortOrder])
C. useMemo(() => sort(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 the hook unconditionally and branch inside its effect or logic
B. Call useState inside the event handler when needed
C. Call useEffect only inside if (enabled)
D. Call different hooks in each branch with matching variable names

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 calculation is guaranteed to use stale props
C. The effect cannot access price after the first render
D. The dependency array prevents all state updates

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. Move title into a ref and keep the array empty
B. Remove the effect and assign the title during module initialization
C. Add title to the dependency array
D. Replace the effect with useCallback(title, [])