import React,
{ render, useState, useEffect } from "react";
function getCount() {
return document.querySelector("p")?.innerText;
}
const LifecycleDemo = () => {
const [count, setCount] = useState(0);
// Runs during rendering
console.log("Rendering: " + getCount())
// Runs only once when the component is mounted
useEffect(() => {
console.log("Mounted: " + getCount());
// Cleanup: Runs when the component unmounts
return () => {
console.log("Unmounted");
};
}, []); // Dependency array is empty,
// so it runs only on mount and unmount.
// Runs every time 'count' changes
useEffect(() => {
console.log(`Updated to "${getCount()}"`);
// Cleanup: Runs before the next effect or on unmount
return () => {
console.log(`Cleanup count changes or unmount: ${count}`);
};
}, [count]); // Dependency array has 'count',
// so it runs when 'count' changes.
return (
<div>
<h1>React Lifecycle with useEffect</h1>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
};
function App() {
const [show, setShow] = useState(true);
return (
<>
{show && <LifecycleDemo />}
<button onClick={() => setShow(!show)}>Toggle</button>
</>
)
}
render(<App />)
body {
padding: 16px;
font-size: 24px;
}
p, h1 {
margin: 2px 0px;
}
h1 {
font-size: 32px;
}