Effects & Lifecycle

5 questions found

What is the useEffect hook used for in React?

Beginner
useEffect lets you run code that reaches outside of React, such as fetching data, setting a timer, or updating the page title, after a component renders. It runs after the screen updates, and you can control exactly when it runs using its dependency array.
function PageTitle({ title }) {
  useEffect(() => {
    document.title = title;
  }, [title]);

  return <h1>{title}</h1>;
}
Real-world example A blog automatically updates the browser tab's title to match whichever article the user is currently reading, using a simple useEffect that runs whenever the title prop changes.

Common follow-ups: What happens if you leave out the dependency array entirely from useEffect?;Why does React run effects after the screen updates instead of before?

Custom Hooks;Hooks

What does the dependency array in useEffect actually control?

Intermediate
The dependency array tells React exactly which values, when changed, should cause the effect to run again. An empty array means the effect runs only once when the component first appears. Leaving it out entirely means the effect runs after every single render, which is rarely what you actually want.
useEffect(() => {
  console.log('Runs only once, when the component first appears');
}, []);

useEffect(() => {
  console.log('Runs every time count changes');
}, [count]);

useEffect(() => {
  console.log('Runs after every single render');
});
Real-world example A search page fetches new results only when the search term actually changes, by listing the search term as the single dependency in its useEffect, avoiding wasted requests on unrelated re renders.

Common follow-ups: What happens if you use a value inside useEffect but forget to include it in the dependency array?;What eslint rule helps catch missing dependencies automatically?

Hooks;Performance (memo/useMemo)

How do you clean up an effect in React, and why is it important?

Intermediate
If an effect sets up something like a timer, a subscription, or an event listener, you should return a cleanup function from useEffect that removes it. React automatically calls this cleanup function before the effect runs again and when the component is removed from the screen, preventing memory leaks and unexpected behavior.
useEffect(() => {
  const timer = setInterval(() => console.log('tick'), 1000);
  return () => clearInterval(timer); // cleanup, stops the timer
}, []);
Real-world example A live clock component correctly stops its timer when the user navigates away from the page, because it returns a cleanup function that clears the interval, avoiding a hidden timer that keeps running forever in the background.

Common follow-ups: What happens if you forget to return a cleanup function for a subscription or timer?;Does the cleanup function run before or after the next effect runs?

Custom Hooks;Performance (memo/useMemo)

How would you fetch data safely inside useEffect while avoiding a common bug called a race condition?

Advanced
A race condition can happen when a component fetches data, the dependency changes again quickly, and an older, slower request finishes after a newer one, showing outdated results by mistake. You fix this by tracking whether the effect is still the current one, usually with a simple flag inside the cleanup function, and ignoring outdated results.
useEffect(() => {
  let isCurrent = true;
  fetchResults(query).then((data) => {
    if (isCurrent) setResults(data);
  });
  return () => { isCurrent = false; };
}, [query]);
Real-world example A search box avoids showing outdated results when a user types quickly, by tracking whether each fetch request is still the most recent one before actually updating the results shown on screen.

Common follow-ups: How does this same problem get solved automatically by a library like React Query?;What other approaches exist for canceling an outdated fetch request entirely?

Data Fetching (React Query & SWR);Effects & Lifecycle

What is the difference between useEffect and code that runs directly during rendering?

Beginner
Code inside useEffect runs after React has already updated the screen, making it safe for things like fetching data or interacting with browser APIs. Code that runs directly during rendering happens while React is figuring out what to display, and should stay free of side effects like network requests, since it might run more than once for the same render.
// Safe, side effects belong inside useEffect
function Page() {
  useEffect(() => {
    logPageView();
  }, []);
  return <h1>Welcome</h1>;
}

// Risky, side effect happens directly during render
function Page() {
  logPageView(); // runs on every single render, even unnecessary ones
  return <h1>Welcome</h1>;
}
Real-world example A developer notices an analytics event was being logged far more often than expected, and fixes the bug by moving the logging call from directly inside the component body into a useEffect with an empty dependency array.

Common follow-ups: Why might a render function run more than once for the same screen update?;What kinds of code are actually safe to run directly during rendering?

Effects & Lifecycle;Hooks