📄Assignments of Class 10: useEffect Basics

Rashmi Mishra
0

 ðŸ“„Assignments of Class 10

useEffect Basics


Assignment 1: Show an alert only when the component first loads

Task:
Create a component that shows an alert "Component has mounted" only once when the component loads.

Solution:

import React, { useEffect } from 'react'; 

function AlertOnMount() {

  useEffect(() => {

    alert('Component has mounted');

  }, []); // empty array means run once on mount

 

  return <div>Check alert on component load!</div>;

} 

export default AlertOnMount;

Explanation:
The empty dependency array [] makes sure the effect runs only once, mimicking componentDidMount.


Assignment 2: Update the document title when input changes

Task:
Create a component with an input box that updates the browser tab title with the text typed.

Solution:

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

function UpdateTitle() {

  const [text, setText] = useState(''); 

  useEffect(() => {

    document.title = text || "React useEffect Demo";

  }, [text]); // Effect runs whenever 'text' changes 

  return (

    <input

      type="text"

      value={text}

      onChange={e => setText(e.target.value)}

      placeholder="Type something here"

    />

  );

}

 

export default UpdateTitle;

Explanation:
Passing [text] ensures the effect runs every time the input text changes.


Assignment 3: Log a message every time the component updates (every render)

Task:
Create a component that logs "Component rendered" to the console every time it renders.

Solution:

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

function LogOnUpdate() {

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

  useEffect(() => {

    console.log("Component rendered");

  }); // No dependency array means runs after every render

 

  return (

    <div>

      <p>Count: {count}</p>

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

    </div>

  );

}

 

export default LogOnUpdate;

Explanation:
Without dependencies, the effect runs after every render.


Assignment 4: Create a timer that updates every second

Task:
Make a component that displays a counter incrementing every second.

Solution:

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

function Timer() {

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

 

  useEffect(() => {

    const intervalId = setInterval(() => {

      setCount(prevCount => prevCount + 1);

    }, 1000);

 

    return () => clearInterval(intervalId); // Cleanup on unmount

  }, []); // Runs once on mount

 

  return <h1>Timer: {count}</h1>;

}

 

export default Timer;

Explanation:
The cleanup function clears the timer when component unmounts.


Assignment 5: Fetch data when the component loads (simulate with setTimeout)

Task:
Simulate fetching data when the component mounts and display "Data loaded".

Solution:

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

function DataFetcher() {

  const [data, setData] = useState(null);

 

  useEffect(() => {

    const timer = setTimeout(() => {

      setData("Data loaded");

    }, 2000);

 

    return () => clearTimeout(timer);

  }, []);

 

  return <div>{data || "Loading..."}</div>;

}

 

export default DataFetcher;

Explanation:
The timeout simulates an async data fetch; the cleanup clears it if unmounted early.


Assignment 6: Change background color on state update and cleanup on unmount

Task:
Change page background color when a button is clicked and reset it on unmount.

Solution:

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

function BackgroundChanger() {

  const [color, setColor] = useState('white');

 

  useEffect(() => {

    document.body.style.backgroundColor = color;

 

    return () => {

      document.body.style.backgroundColor = 'white'; // cleanup

    };

  }, [color]); // Run when 'color' changes

 

  return (

    <button onClick={() => setColor(color === 'white' ? 'lightblue' : 'white')}>

      Toggle Background Color

    </button>

  );

}

 

export default BackgroundChanger;

Explanation:
The cleanup resets the background when component unmounts.


Assignment 7: Display a clock that updates every second (Homework solution)

Task:
Create a digital clock that shows current time and updates every second.

Solution:

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

function Clock() {

  const [time, setTime] = useState(new Date());

 

  useEffect(() => {

    const timerId = setInterval(() => {

      setTime(new Date());

    }, 1000);

 

    return () => clearInterval(timerId);

  }, []);

 

  return <h2>{time.toLocaleTimeString()}</h2>;

}

 

export default Clock;

Explanation:
The state updates every second with the current time.


Assignment 8: useEffect with multiple dependencies

Task:
Create two inputs for first and last name and update full name in the document title whenever either changes.

Solution:

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

function FullNameTitle() {

  const [firstName, setFirstName] = useState('');

  const [lastName, setLastName] = useState('');

 

  useEffect(() => {

    document.title = `${firstName} ${lastName}`.trim() || 'React App';

  }, [firstName, lastName]); // Depend on both inputs 

  return (

    <div>

      <input

        type="text"

        placeholder="First name"

        value={firstName}

        onChange={e => setFirstName(e.target.value)}

      />

      <input

        type="text"

        placeholder="Last name"

        value={lastName}

        onChange={e => setLastName(e.target.value)}

      />

    </div>

  );

}

 

export default FullNameTitle;

Explanation:
The effect runs when either firstName or lastName changes.


Assignment 9: useEffect cleanup for event listeners

Task:
Add a window resize event listener that updates width in state and clean it up on unmount.

Solution:

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

function WindowWidth() {

  const [width, setWidth] = useState(window.innerWidth); 

  useEffect(() => {

    const handleResize = () => setWidth(window.innerWidth); 

    window.addEventListener('resize', handleResize); 

    return () => window.removeEventListener('resize', handleResize); // cleanup

  }, []);

 

  return <div>Window width: {width}px</div>;

}

 

export default WindowWidth;

Explanation:
The cleanup removes the event listener to avoid memory leaks.


Assignment 10: Conditional effect execution with state

Task:
Create a button that toggles a message showing/hiding and logs to console only when the message is shown.

Solution:

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

function ToggleMessage() {

  const [show, setShow] = useState(false);

 

  useEffect(() => {

    if (show) {

      console.log("Message is shown");

    }

  }, [show]); // Runs only when 'show' changes

 

  return (

    <div>

      <button onClick={() => setShow(prev => !prev)}>

        {show ? "Hide" : "Show"} Message

      </button>

      {show && <p>This is the message!</p>}

    </div>

  );

}

 

export default ToggleMessage;

Explanation:
Effect runs only when show changes, and only logs if message is visible.


Summary

These assignments cover:

  • Basic useEffect on mount, update, and cleanup.
  • Dependency arrays and how they control effect runs.
  • Practical uses like timers, event listeners, DOM updates, and conditional effects.

Post a Comment

0Comments

Post a Comment (0)