React Props
Props are arguments passed into React components.
Props are passed to components via HTML attributes.
example:
Example: Updating the document title with useEffect
import React, { useState, useEffect } from "react";
function Counter() {
const [count, setCount] = useState(0);
// useEffect runs after every render
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // dependency array
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default Counter;
Explanation
useState(0) β creates a state variable count.
useEffect(() => { ... }, [count]) β runs the effect whenever count changes.
Inside the effect, we update the document title with the latest count.
The dependency array [count] ensures the effect runs only when count changes, not on every render.
- Run Only Once
jsx
useEffect(() => {
console.log("Component Mounted");
}, []);
Dependency array: []
- Run on Every Render
jsx
useEffect(() => {
console.log("Rendered");
});
- Run When State Changes
jsx
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Count changed");
}, [count]);
- Two States, One Effect
jsx
const [count, setCount] = useState(0);
const [name, setName] = useState("");
useEffect(() => {
console.log("Count or Name changed");
}, [count, name]);
- Derived Logic Show "Even Number" when count is even..
jsx
<p>{count % 2 === 0 ? "Even Number" : "Odd Number"}</p>
- API Call on Mount
jsx
useEffect(() => {
fetch("/api/users")
.then(res => res.json())
.then(data => console.log(data));
}, []);
- Infinite Loop Trap
jsx
useEffect(() => {
setCount(count + 1);
}, [count]);
- Fix the Infinite Loop
jsx
useEffect(() => {
setCount(count + 1);
}, []);
- Document Title Sync
jsx
useEffect(() => {
document.title = count;
}, [count]);
Dependency array: [count]
- Cleanup Basic
jsx
useEffect(() => {
window.addEventListener("click", handleClick);
return () => {
window.removeEventListener("click", handleClick);
};
}, []);
Top comments (0)