React js useEffect Hook Practice Questions with Solutions

Introduction

The useEffect Hook is used in React to synchronize a component with external systems and handle side-effect logic. It can be used for tasks such as updating the document title, working with browser APIs, subscribing to external data, or fetching data. In this chapter, we will solve practical useEffect questions to understand when and how it should be used in React applications. React js useEffect Hook practice questions help to understand the concepts.

1. What is the useEffect Hook in React?

The useEffect Hook is a React Hook used to perform side-effect logic and synchronize a component with external systems.

For example, you can use useEffect to:

  • Update the browser document title
  • Fetch data from an API
  • Work with browser APIs
  • Connect to external services
  • Subscribe to external data

Basic syntax:

import { useEffect } from "react";

function App() {
  useEffect(() => {
    console.log("Effect executed");
  });

  return <h1>Hello React</h1>;
}


2. Why is useEffect used in React?

useEffect is useful when a component needs to perform an operation that is not simply calculating JSX from its current props and state.

For example, updating the browser title is an external effect:

import { useEffect } from "react";

function App() {
  useEffect(() => {
    document.title = "My React App";
  });

  return <h1>Welcome</h1>;
}

export default App;

Here, React renders the component and the effect synchronizes the browser’s document title.


3. How do you use useEffect in a React component?

First, import useEffect from React.

import { useEffect } from "react";

Then call it inside the component:

function App() {
  useEffect(() => {
    console.log("Component effect");
  });

  return <h1>React App</h1>;
}

The function passed to useEffect contains the effect logic.


4. When does useEffect run?

The timing of useEffect depends on its dependency array.

Without a dependency array:

useEffect(() => {
  console.log("Effect executed");
});

The effect runs after every completed render/commit.

With an empty dependency array:

useEffect(() => {
  console.log("Effect executed");
}, []);

It runs after the initial mount in the normal lifecycle.

With dependencies:

useEffect(() => {
  console.log("Count changed");
}, [count]);

The effect runs after commits where count has changed.

Note: In development, React Strict Mode can intentionally run an extra setup/cleanup cycle to help find effect-related bugs.


5. How do you use useEffect with an empty dependency array?

An empty dependency array [] tells React that the effect does not depend on changing reactive values.

Example:

import { useEffect } from "react";

function App() {
  useEffect(() => {
    console.log("Initial effect");
  }, []);

  return <h1>Welcome to React</h1>;
}

export default App;

This effect runs after the component is initially mounted.

A common use case is setting up something that should happen once for the component’s mounted lifetime.


6. How do you use useEffect when a state value changes?

You can place a state variable inside the dependency array.

Example:

import { useEffect, useState } from "react";

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

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

  return (
    <div>
      <h2>Count: {count}</h2>

      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

export default Counter;

Whenever count changes, React runs the effect after the corresponding commit.


7. How do you use useEffect to update the document title?

The browser document title can be updated using document.title.

import { useEffect, useState } from "react";

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

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <div>
      <h2>Count: {count}</h2>

      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

export default Counter;

Now, whenever the count changes, the browser tab title is updated.

This is a simple example of using useEffect to synchronize React state with an external browser API.


8. How do you use useEffect for API/data fetching?

useEffect can be used for data fetching when a component needs to load data from an external API.

Example:

import { useEffect, useState } from "react";

function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    async function loadUsers() {
      const response = await fetch(
        "https://jsonplaceholder.typicode.com/users"
      );

      const data = await response.json();
      setUsers(data);
    }

    loadUsers();
  }, []);

  return (
    <div>
      <h2>Users</h2>

      {users.map((user) => (
        <p key={user.id}>{user.name}</p>
      ))}
    </div>
  );
}

export default Users;

Here:

  1. The component renders.
  2. The effect starts the data-fetching operation.
  3. The API response is converted to JSON.
  4. setUsers() updates the state.
  5. React renders the user list.

More advanced API handling, loading states, errors, and dependencies will be covered in later chapters.


9. How do you use useEffect with multiple dependencies?

You can provide multiple dependencies inside the dependency array.

Example:

import { useEffect } from "react";

function Profile({ name, age }) {
  useEffect(() => {
    console.log("Name or age changed");
    console.log(name, age);
  }, [name, age]);

  return (
    <div>
      <h2>{name}</h2>
      <p>Age: {age}</p>
    </div>
  );
}

export default Profile;

The effect is synchronized whenever either name or age changes.

The dependency array should contain the reactive values used by the effect that it needs to stay synchronized with.


10. Build a Practical Counter using useEffect

Create a counter that updates the browser document title whenever the count changes.

Solution:

import { useEffect, useState } from "react";

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

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  const increase = () => {
    setCount((previousCount) => previousCount + 1);
  };

  const decrease = () => {
    setCount((previousCount) => previousCount - 1);
  };

  return (
    <div>
      <h1>Counter</h1>

      <h2>{count}</h2>

      <button onClick={increase}>Increase</button>
      <button onClick={decrease}>Decrease</button>
    </div>
  );
}

export default Counter;

How it works:

  • useState() stores the counter value.
  • setCount() updates the state.
  • useEffect() synchronizes the browser title with the current count.
  • [count] tells React that the effect depends on count.
  • The functional updater ensures the new count is calculated from the previous state.

This is a simple practical example of combining useState and useEffect.

Key Takeaways

  • useEffect is a React Hook for synchronizing with external systems and handling effects.
  • It can work with browser APIs, API requests, subscriptions, and other external operations.
  • The dependency array controls when an effect needs to re-synchronize.
  • An empty dependency array [] is commonly used for effects that do not depend on changing reactive values.
  • Dependencies such as [count] make an effect respond to changes in those values.
  • useEffect should not be used for every piece of logic in a component.
  • Values that can be calculated directly during rendering usually do not need an effect.
  • React Strict Mode may run an additional setup/cleanup cycle in development.
  • useEffect works especially well with other Hooks such as useState.
  • Proper effect dependencies are important for predictable React applications.

FAQs

1. What is the useEffect Hook in React?

useEffect is a React Hook used to synchronize a component with external systems and perform side-effect logic.

2. Why do we use useEffect in React?

It is used for tasks such as API requests, browser API interactions, subscriptions, and synchronizing external systems with React state or props.

3. What happens when useEffect has no dependency array?

Without a dependency array, the effect runs after every completed render/commit.

4. What does an empty dependency array [] mean?

An empty dependency array means the effect does not depend on changing reactive values. It normally runs after the component’s initial mount.

5. Can useEffect depend on state?

Yes. You can add state variables to the dependency array.

useEffect(() => {
  console.log(count);
}, [count]);

6. Can we fetch API data using useEffect?

Yes. useEffect is commonly used to start data-fetching logic when a component needs to synchronize with an external API.

7. Should useEffect be used for every calculation?

No. If a value can be calculated directly from existing props or state during rendering, an effect is usually unnecessary. Effects are mainly useful for synchronization with external systems.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top