function EffectsDemoTwoStatesWithDependeny() {
const [title, setTitle] = useState("default title");
const titleRef = useRef();
const [darkMode, setDarkMode] = useState(false);
useEffect(() => {
console.log("useEffect");
document.title = title;
}, [title]);
console.log("render");
const handleClick = () => setTitle(titleRef.current.value);
const handleCheckboxChange = () => setDarkMode((prev) => !prev);
return (
<div className={darkMode ? "view dark-mode" : "view"}>
<label htmlFor="darkMode">dark mode</label>
<input
name="darkMode"
type="checkbox"
checked={darkMode}
onChange={handleCheckboxChange}
/>
<input ref={titleRef} />
<button onClick={handleClick}>change title</button>
</div>
);
}
import { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Runs ONCE after initial rendering
}, []);
}
import { useEffect, useState } from 'react';
function MyComponent({ prop }) {
const [state, setState] = useState('');
useEffect(() => {
// Runs ONCE after initial rendering
// and after every rendering ONLY IF `prop` or `state` changes
}, [prop, state]);
}