Bird
Raised Fist0
Reactframework~5 mins

What is useEffect in React

Choose your learning style10 modes available
Introduction

useEffect helps your React component do things after it shows up on the screen or when something changes. It's like telling your app to react to changes or do side jobs.

Load data from the internet when a page opens
Update the page title when a user changes something
Set up a timer or interval that runs repeatedly
Clean up resources like stopping a timer when the component goes away
Syntax
React
useEffect(() => {
  // code to run
  return () => {
    // cleanup code (optional)
  };
}, [dependencies]);

The first argument is a function that runs after the component renders.

The second argument is an array of dependencies that tell React when to run the effect again.

Examples
This runs after every time the component renders.
React
useEffect(() => {
  console.log('Runs after every render');
});
Empty array means it runs only once when the component first appears.
React
useEffect(() => {
  console.log('Runs only once when component mounts');
}, []);
This runs only when the count value changes.
React
useEffect(() => {
  console.log('Runs when count changes:', count);
}, [count]);
Sample Program

This component shows seconds passed since it appeared. It uses useEffect to start a timer when the component mounts and cleans it up when it unmounts.

React
import React, { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(s => s + 1);
    }, 1000);

    return () => clearInterval(interval); // cleanup on unmount
  }, []);

  return (
    <div>
      <p>Seconds passed: {seconds}</p>
    </div>
  );
}

export default Timer;
OutputSuccess
Important Notes

Always clean up timers or subscriptions inside useEffect to avoid bugs.

If you forget the dependency array, the effect runs after every render, which can slow your app.

Summary

useEffect runs code after rendering or when data changes.

Use it to load data, update things, or clean up resources.

Remember the dependency array controls when it runs.

Practice

(1/5)
1. What is the primary purpose of useEffect in React?
easy
A. To declare state variables inside a component
B. To create new components dynamically
C. To run code after the component renders or when data changes
D. To style components with CSS

Solution

  1. Step 1: Understand what useEffect does

    useEffect runs code after the component renders or when specified data changes.
  2. Step 2: Compare with other React features

    State variables declare data, styling is CSS, and creating components is unrelated to useEffect.
  3. Final Answer:

    To run code after the component renders or when data changes -> Option C
  4. Quick Check:

    useEffect runs code after render or data change [OK]
Hint: useEffect runs after render or data updates [OK]
Common Mistakes:
  • Confusing useEffect with useState
  • Thinking useEffect styles components
  • Believing useEffect creates components
2. Which of the following is the correct syntax to use useEffect that runs only once after the first render?
easy
A. useEffect(() => { console.log('Hello'); });
B. useEffect(() => { console.log('Hello'); }, []);
C. useEffect(() => { console.log('Hello'); }, true);
D. useEffect(() => { console.log('Hello'); }, null);

Solution

  1. Step 1: Identify how to run useEffect once

    Passing an empty array [] as dependency makes useEffect run only once after the first render.
  2. Step 2: Check other options

    Without dependencies (useEffect(() => { console.log('Hello'); });), it runs after every render. Options B and C pass non-array values, causing the effect to run after every render (with a React warning).
  3. Final Answer:

    useEffect(() => { console.log('Hello'); }, []); -> Option B
  4. Quick Check:

    Empty dependency array means run once [OK]
Hint: Empty array runs useEffect once after first render [OK]
Common Mistakes:
  • Omitting dependency array causes repeated runs
  • Passing non-array values thinking it runs once
  • Confusing [] with null or true
3. What will be logged to the console when this component runs?
import React, { useState, useEffect } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log('Count is:', count);
  }, [count]);

  return (
    <button onClick={() => setCount(count + 1)}>Increment</button>
  );
}
medium
A. Logs 'Count is: 0' and then logs updated count each time button clicked
B. Logs 'Count is: 0' once after first render only
C. Logs nothing because useEffect has no dependencies
D. Causes an infinite loop of logs

Solution

  1. Step 1: Understand useEffect with [count] dependency

    The effect runs after first render and every time count changes, logging the current count.
  2. Step 2: Analyze button click behavior

    Clicking the button increases count, triggering useEffect to log the new value.
  3. Final Answer:

    Logs 'Count is: 0' and then logs updated count each time button clicked -> Option A
  4. Quick Check:

    useEffect runs on count change, logging each update [OK]
Hint: useEffect runs after render and on dependency change [OK]
Common Mistakes:
  • Thinking useEffect runs only once without empty array
  • Believing no logs happen without empty array
  • Assuming infinite loops without setCount inside useEffect
4. Identify the problem in this code snippet using useEffect:
useEffect(() => {
  fetchData();
}, fetchData);

Assume fetchData is a function defined outside.
medium
A. No problem, this code is correct
B. fetchData cannot be called inside useEffect
C. useEffect must not have any dependencies
D. Dependency array should be an array, not a function

Solution

  1. Step 1: Check dependency argument type

    The second argument to useEffect must be an array listing dependencies, not a function.
  2. Step 2: Identify correct syntax

    It should be [fetchData] if fetchData is a dependency, not just fetchData alone.
  3. Final Answer:

    Dependency array should be an array, not a function -> Option D
  4. Quick Check:

    useEffect dependencies must be an array [OK]
Hint: Dependency argument must be an array, not a function [OK]
Common Mistakes:
  • Passing a function instead of an array as dependencies
  • Ignoring dependency array causing repeated runs
  • Thinking useEffect cannot call functions
5. You want to fetch user data only once when a component mounts and clean up a subscription when it unmounts. Which useEffect pattern is correct?
useEffect(() => {
  const subscription = subscribeToUserData();
  fetchUserData();
  return () => {
    subscription.unsubscribe();
  };
}, []);
hard
A. This pattern correctly fetches once and cleans up on unmount
B. Missing dependency array causes multiple fetches
C. Cleanup function should not be returned inside useEffect
D. Subscription should be created inside cleanup function

Solution

  1. Step 1: Check dependency array usage

    Empty array [] ensures effect runs once on mount and cleanup on unmount.
  2. Step 2: Verify cleanup function correctness

    Returning a function that unsubscribes cleans up resources properly when component unmounts.
  3. Final Answer:

    This pattern correctly fetches once and cleans up on unmount -> Option A
  4. Quick Check:

    Empty array + cleanup function = run once + cleanup [OK]
Hint: Empty array runs once; return cleanup function for unmount [OK]
Common Mistakes:
  • Omitting cleanup function causing memory leaks
  • Not using empty array causing repeated fetches
  • Placing subscription inside cleanup function incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard