<div id='root' ></div>
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #1a1d1d;
padding: 20px;
font-size: 0.875rem;
}
button {
background-color: #4caf50;
color: white;
padding: 10px 15px;
margin: 5px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
max-width: 30rem;
margin: auto;
}
.controls-container {
display: flex;
justify-content: space-evenly;
margin-bottom: 8px;
gap: 4px;
}
.bad-practice-button {
background-color: #e73e31; /* Red color */
}
.bad-practice-button:hover {
background-color: #d32f2f; /* Darker red on hover */
}
@media screen and (max-width: 600px) {
body {
padding: 5px;
}
.container {
width: 100%;
}
}
import React, {
useState,
useRef,
useEffect
} from "https://esm.sh/react@18.2.0";
import ReactDOM from "https://esm.sh/react-dom@18.2.0";
const App = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log(`Count updated to: ${count}`);
}, [count]);
const handleClick = () => {
setCount(count + 1);
console.log(count); // This will log the previous state value, not the updated one
};
const incrementCount3Times = () => {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
};
const functionalIncrement3Times = () => {
functionalIncrement();
functionalIncrement();
functionalIncrement();
};
const updateCountInLoop = () => {
for (let i = 0; i < 5; i++) {
setCount(count + 1);
}
};
const functionalIncrement = () => {
setCount((prevCount) => prevCount + 1);
};
return (
<div className="container">
<p>Count: {count}</p>
<div className="controls-container">
<button className="bad-practice-button" onClick={handleClick}>Increment Count</button>
<button className="bad-practice-button" onClick={incrementCount3Times}>Increment Count 3 times </button>
<button className="bad-practice-button" onClick={updateCountInLoop}>Update Count in a loop </button>
</div>
<button onClick={functionalIncrement3Times}>
Correct way to update 3 times using a function for the setter parameter{" "}
</button>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
View Compiled
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.