React › Effects & Lifecycle
What is the difference between useEffect and code that runs directly during rendering?
BeginnerAnswer
Code inside useEffect runs after React has already updated the screen, making it safe for things like fetching data or interacting with browser APIs. Code that runs directly during rendering happens while React is figuring out what to display, and should stay free of side effects like network requests, since it might run more than once for the same render.
// Safe, side effects belong inside useEffect
function Page() {
useEffect(() => {
logPageView();
}, []);
return <h1>Welcome</h1>;
}
// Risky, side effect happens directly during render
function Page() {
logPageView(); // runs on every single render, even unnecessary ones
return <h1>Welcome</h1>;
}Real-world example A developer notices an analytics event was being logged far more often than expected, and fixes the bug by moving the logging call from directly inside the component body into a useEffect with an empty dependency array.