Learn how to use the useEffect hook in React to handle side effects like API calls and event listeners. This blog covers its syntax, examples, dependency management, and cleanup functions with MCQs for better understanding. #ReactJS #useEffect #WebDevelopment

Understanding useEffect in React – Part 1

Introduction to useEffect

React’s useEffect is one of the most powerful hooks that allows us to handle side effects in functional components. Side effects include tasks such as fetching data from an API, interacting with the browser's DOM, or subscribing to external events.

In this blog, we’ll break down useEffect step by step, using a practical example.

What is useEffect?

useEffect is a hook that lets you perform side effects in function components. It runs after the component renders and can be configured to re-run under specific conditions.

Syntax:

useEffect(() => {

  // Side effect logic here

}, [dependencies]);

  • The first argument is a function that contains the side effect logic.
  • The second argument is an array of dependencies. When any dependency changes, the effect runs again.

Practical Example: Fetching User Data with useEffect

Let’s create a React component that fetches user data from an API whenever a user ID changes.

Code Implementation:

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

function UserData() {

  const [userId, setUserId] = useState(1);

  const [user, setUser] = useState(null);

  useEffect(() => {

    fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)

      .then((response) => response.json())

      .then((data) => setUser(data));

  }, [userId]);

  return (

    <div>

      <h1>User Info</h1>

      {user && (

        <div>

          <p>Name: {user.name}</p>

          <p>Email: {user.email}</p>

          <p>Phone: {user.phone}</p>

        </div>

      )}

    </div>

  );

}

export default UserData;

How useEffect Works in This Example

  1. Initial Render: The component renders with userId = 1 and user = null.
  2. API Call Triggered: useEffect runs after the first render and fetches data for user ID 1.
  3. State Update: Once data is fetched, setUser(data) updates the user state.
  4. Re-render: The component re-renders with the new user data, displaying the name, email, and phone.
  5. Dependency Array ([userId]): If userId changes, useEffect runs again to fetch new data.

Key Points About useEffect

  • Runs after render: Unlike class components where lifecycle methods like componentDidMount are used, useEffect runs after the component renders.
  • Dependency Array: If left empty ([]), useEffect runs only once (on mount). If dependencies are provided, it runs whenever they change.
  • Cleanup Function: You can return a function from useEffect to clean up effects like event listeners.

Example of Cleanup Function:

useEffect(() => {

  const interval = setInterval(() => {

    console.log("This runs every second");

  }, 1000); 

  return () => clearInterval(interval); // Cleanup

}, []);

Conclusion

This was an introduction to useEffect in React. In Part 2, we’ll cover advanced use cases, such as handling multiple effects, dependency optimizations, and cleanup functions in-depth.

MCQs on useEffect in React

1. What is the primary purpose of useEffect in React?

a) To handle form validation
b) To manage side effects in functional components
c) To create reusable components
d) To define state variables

2. When does the useEffect hook execute by default?

a) Only when the component mounts
b) Every time the component re-renders
c) When the component is unmounted
d) Only when the dependency array is provided

3. How can you prevent useEffect from running on every re-render?

a) By not using useEffect
b) By passing an empty dependency array []
c) By using setState inside useEffect
d) By calling useEffect inside a loop

4. What does the dependency array in useEffect do?

a) It determines when useEffect should re-run
b) It stores component state
c) It prevents side effects from executing
d) It forces a component to re-render

5. In the given UserData component, what will happen if userId is updated?

a) useEffect will not run again
b) useEffect will fetch new user data based on the updated userId
c) The component will crash
d) The previous user’s data will be lost without an update

6. How can you clean up side effects in useEffect?

a) By using a return statement inside useEffect
b) By calling useEffect multiple times
c) By using useState
d) By setting state to null

7. Which of the following is an example of a side effect in React?

a) Updating state within the render method
b) Modifying the DOM directly
c) Declaring a variable inside a component
d) Using map() to render a list

8. What happens if no dependency array is provided to useEffect?

a) The effect runs only once
b) The effect runs only when the component is unmounted
c) The effect runs after every render
d) The effect will never run

9. How can you make useEffect run only once, similar to componentDidMount in class components?

a) By not using useEffect
b) By passing an empty dependency array []
c) By using setTimeout inside useEffect
d) By calling useEffect inside setState

10. Which of the following statements about useEffect is FALSE?

a) useEffect can be used for fetching data from an API
b) useEffect is a replacement for lifecycle methods in class components
c) useEffect must always have a dependency array
d) useEffect can be

used to set up event listeners


Correct Answers:

1. b) To manage side effects in functional components
2. b) Every time the component re-renders
3. b) By passing an empty dependency array []
4. a) It determines when useEffect should re-run
5. b) useEffect will fetch new user data based on the updated userId
6. a) By using a return statement inside useEffect.
7. b) Modifying the DOM directly
8. c) The effect runs after every render
9. b) By passing an empty dependency array [].
10. c) useEffect must always have a dependency array

To know more, visit our YOUTUBE Channel

Download Lecture Pdf..

Leave a Comment

Get a Call Back from Our Career Assistance Team Request Callback
WhatsApp