Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views19 pages

Reactjs Unit III

The document provides a comprehensive guide on implementing timers in ReactJS using hooks like useState and useEffect. It includes examples of a timer component, a countdown timer, and a time-logging app, detailing how to manage and delete timers to prevent memory leaks. Key features include dynamic input, time formatting, and the ability to log elapsed time for tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views19 pages

Reactjs Unit III

The document provides a comprehensive guide on implementing timers in ReactJS using hooks like useState and useEffect. It includes examples of a timer component, a countdown timer, and a time-logging app, detailing how to manage and delete timers to prevent memory leaks. Key features include dynamic input, time formatting, and the ability to log elapsed time for tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 19

UNIT- III

Components and Servers


Components Part II
Case Study: Time-logging app
Updating timers

To update timers in ReactJS, you can use


the useEffect hook along with setInterval to
manage the timer's lifecycle.
Example: Timer Component in ReactJS

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


const Timer = () => {
const [seconds, setSeconds] = useState(0); // State to track elapsed time
useEffect(() => {
// Start the timer when the component mounts
const interval = setInterval(() => {
setSeconds((prevSeconds) => prevSeconds + 1); // Increment seconds
}, 1000);

// Cleanup function to clear the interval when the component unmounts


return () => {
clearInterval(interval); }; }, []); // Empty dependency array ensures this
runs only once return
(
<div>
<h1>Timer: {seconds} seconds</h1> </div> );
};
export default Timer;
Explanation:
State Management:
 useState is used to track the number of seconds elapsed.
Effect Hook:
 useEffect is used to set up the timer when the component mounts.
 The setInterval function increments the seconds state every 1000

milliseconds (1 second).
 The cleanup function (clearInterval) ensures the timer is stopped

when the component unmounts, preventing memory leaks.


Dependency Array:
 The empty array [] ensures the useEffect runs only once when the
component is mounted.
Example: Countdown Timer with User Input
import React, { useState, useEffect } from "react";
const CountdownTimer = () => {
const [timeLeft, setTimeLeft] = useState(0); // State to track
remaining time const [isRunning, setIsRunning] = useState(false); //
State to track if the timer is running

useEffect(() => {
let timer;
if (isRunning && timeLeft > 0) {
timer = setInterval(() => {
setTimeLeft((prevTime) => prevTime - 1); // Decrement time
}, 1000); } // Cleanup function to clear the interval

return () => {
clearInterval(timer);
};
}, [isRunning, timeLeft]); // Re-run effect when isRunning or
timeLeft changes
const startTimer = () => {
if (timeLeft > 0) {
setIsRunning(true);
}
};
const stopTimer = () => {
setIsRunning(false);
};
const resetTimer = () => {
setIsRunning(false);
setTimeLeft(0);
};
return (
<div>
<h1>Countdown Timer: {timeLeft} seconds</h1>
<input type="number“
placeholder="Enter time in seconds"
onChange={(e) => setTimeLeft(Number(e.target.value))}
disabled={isRunning}
/>
<button onClick={startTimer} disabled={isRunning || timeLeft <=
0}> Start
</button>
<button onClick={stopTimer} disabled={!isRunning}> Stop
</button>
<button onClick={resetTimer}>Reset</button>
</div> );
};
export default CountdownTimer;
Key Features:
Dynamic Input:
 The user can input the countdown time in seconds.
Start/Stop/Reset:
 Buttons allow the user to control the timer.
Effect Dependencies:
 The useEffect hook listens to changes
in isRunning and timeLeft to manage the timer dynamically.
Time-logging app: Updating timers
To implement and update timers in a ReactJS time-
logging app, you can use React's state management and
lifecycle hooks like useState and useEffect. Below is a
complete example of how to create a timer that updates every
second and integrates seamlessly into a time-logging app.
Example: Timer Component for Time Logging App
import React, { useState, useEffect } from "react";
const Timer = ({ taskName, onLogTime }) => {
const [elapsedTime, setElapsedTime] = useState(0); // Time in
seconds
const [isRunning, setIsRunning] = useState(false); // Start or stop
the timer
const toggleTimer = () => {
setIsRunning((prev) => !prev); }; // Reset the timer
const resetTimer = () => {
setElapsedTime(0);
setIsRunning(false);
}; // Log the time and reset
const logTime = () => {
onLogTime(taskName, elapsedTime); // Pass the task name and
elapsed time to the parent
resetTimer(); }; // Update the timer every second when running
useEffect(() => {
let timerId;
if (isRunning) {
timerId = setInterval(() => {
return () => clearInterval(timerId); // Cleanup on unmount or when
isRunning changes
}, [isRunning]); // Format time in HH:MM:SS
const formatTime = (seconds) => {
const hrs = Math.floor(seconds / 3600);
const mins = Math.floor((seconds % 3600) / 60
const secs = seconds % 60;
return `${hrs.toString().padStart(2, "0")}:$
{mins .toString() .padStart(2, "0")}:${secs.toString().padStart(2,
"0")}`; };
return (
<div style={{ marginBottom: "20px" }}>
<h3>Task: {taskName}</h3>
<p>Elapsed Time: {formatTime(elapsedTime)}</p>
<button onClick={toggleTimer}> {isRunning ? "Pause" : "Start"}
</button> <button onClick={resetTimer} disabled={!isRunning
&& elapsedTime === 0}> Reset </button>
<button onClick={logTime} disabled={elapsedTime === 0}> Log
Time </button> </div> );
};
const TimeLoggingApp = () => {
const [logs, setLogs] = useState([]); // Handle logging time for a
task
const handleLogTime = (taskName, time) => {
setLogs((prevLogs) => [ ...prevLogs, { taskName, time, loggedAt:
new Date().toLocaleString() }, ]);
};
return (
<div>
<h1>Time Logging App</h1>
<Timer taskName="Task 1" onLogTime={handleLogTime} />
<Timer taskName="Task 2" onLogTime={handleLogTime} />
<h2>Logged Times</h2>
<ul> {logs.map((log, index) => ( <li key={index}> Task:
{log.taskName}, Time: {log.time}s, Logged At: {log.loggedAt} </li>
))}
</ul>
</div>
);
};
export default TimeLoggingApp;
Key Features:
Timer Component:
 Tracks elapsed time for a specific task.
 Allows starting, pausing, resetting, and logging time.

 Uses useEffect to update the timer every second when running.

Parent Component:
 Manages a list of logged times.
 Displays logs with task names, elapsed time, and timestamps.

Time Formatting:
 Converts seconds into HH:MM:SS format for better readability.
Dynamic Task Support:
 Multiple Timer components can be added for different tasks.
Deleting timers in ReactJS
In React, managing timers (like those
created with setTimeout or setInterval) is
crucial to avoid memory leaks or unexpected
behavior, especially when components
unmount or re-render. Below is a guide on
how to properly delete timers in React using
hooks.
Example: Clearing a Timer with setTimeout
import React, { useEffect, useState } from "react";
function TimerComponent() {
const [count, setCount] = useState(0);
useEffect(() => { // Set up a timer
const timer = setTimeout(() => {
setCount((prevCount) => prevCount + 1); }, 1000); // Cleanup
function to clear the timer
return () => {
clearTimeout(timer);
};
}, [count]); // Dependency array ensures the timer resets when
`count` changes return (
<div>
<h1>Count: {count}</h1>
</div> );
}
export default TimerComponent;
Explanation:
setTimeout: A timer is set to increment the count after 1
second.
Cleanup with clearTimeout: The return function
inside useEffect ensures the timer is cleared when the
component unmounts or before the effect re-runs (e.g.,
when count changes).
Time-logging app: Deleting timers
To delete timers in a React-based
application like react-time-logging, you need
to ensure proper cleanup of timers to prevent
memory leaks or unexpected behavior. This
typically involves clearing timers created
with setTimeout or setInterval when the
component unmounts or when the timer is no
longer needed.
Example: Managing and Deleting Timers
import React, { useState, useEffect } from "react";
const TimerComponent = () => {
const [time, setTime] = useState(0);
const [isRunning, setIsRunning] = useState(false);
let timerId = null; // Timer ID for reference
// Start the timer
const startTimer = () => {
if (!isRunning) {
setIsRunning(true);
timerId = setInterval(() => {
setTime((prevTime) => prevTime + 1); }, 1000); // Increment time
every second
}
}; // Stop the timer
const stopTimer = () => {
setIsRunning(false);
clearInterval(timerId); // Clear the interval
}; // Reset the timer
const resetTimer = () => {
stopTimer();
unmount useEffect(() => {
return () => {
clearInterval(timerId); // Ensure timer is cleared }; }, []);
return (
<div>
<h1>Time: {time}s</h1>
<button onClick={startTimer} disabled={isRunning}> Start
</button>
<button onClick={stopTimer} disabled={!isRunning}> Stop
</button>
<button onClick={resetTimer}>Reset</button>
</div> );
};
export default TimerComponent;

You might also like