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
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
Step 1: Understand what useEffect does
useEffect runs code after the component renders or when specified data changes.
Step 2: Compare with other React features
State variables declare data, styling is CSS, and creating components is unrelated to useEffect.
Final Answer:
To run code after the component renders or when data changes -> Option C
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
Step 1: Identify how to run useEffect once
Passing an empty array [] as dependency makes useEffect run only once after the first render.
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).
Final Answer:
useEffect(() => { console.log('Hello'); }, []); -> Option B
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?