0
0
Reactframework~10 mins

Dependency array usage in React - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to run the effect only once when the component mounts.

React
useEffect(() => {
  console.log('Component mounted');
}, [1]);
Drag options to blanks, or click blank then click option'
A[null]
B[true]
C[]
D[0]
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-empty array causes the effect to run more than once.
Leaving out the dependency array runs the effect on every render.
2fill in blank
medium

Complete the code to run the effect whenever the 'count' state changes.

React
useEffect(() => {
  console.log(`Count changed to ${count}`);
}, [1]);
Drag options to blanks, or click blank then click option'
A[count]
B[count, setCount]
C[setCount]
D[]
Attempts:
3 left
💡 Hint
Common Mistakes
Using an empty array means the effect won't run on count changes.
Including setter functions like setCount is unnecessary.
3fill in blank
hard

Fix the error in the effect to avoid missing dependencies warning.

React
useEffect(() => {
  console.log(`User: ${user.name}`);
}, [1]);
Drag options to blanks, or click blank then click option'
A[user]
B[]
C[user.name]
D[name]
Attempts:
3 left
💡 Hint
Common Mistakes
Leaving the dependency array empty causes stale data or warnings.
Using a non-existent variable like 'name' causes errors.
4fill in blank
hard

Fill both blanks to run the effect when either 'propA' or 'stateB' changes.

React
useEffect(() => {
  console.log('Effect triggered');
}, [1]); // dependencies

const [stateB, setStateB] = useState(0);

// props: propA

// Effect depends on [2] and stateB
Drag options to blanks, or click blank then click option'
A[propA, stateB]
BpropA
CstateB
D[]
Attempts:
3 left
💡 Hint
Common Mistakes
Listing only one dependency causes missed updates.
Using an empty array means the effect never reruns.
5fill in blank
hard

Fill all three blanks to create a memoized callback that updates 'count' and depends on 'count' and 'setCount'.

React
const increment = useCallback(() => {
  [1](count + 1);
}, [2]); // dependencies

// Variables used: count, setCount

// Dependency array: [3]
Drag options to blanks, or click blank then click option'
AsetCount
B[count, setCount]
Ccount
D[]
Attempts:
3 left
💡 Hint
Common Mistakes
Leaving the dependency array empty causes stale closures.
Not calling the setter function correctly.