SkillPilotAI

useEffect part 1

useEffect is the place for side effects: work that touches the world outside render, like timers, API calls, the tab title or localStorage. It runs after React commits, and its dependency array and cleanup decide when it runs again and how it is stopped.

32.1 The problem: a timer inside render

  • The Clock component calls setInterval directly in the component body.
  • Expected one second at a time, but the screen jumps 0 -> 3 -> 10: the clock gets faster every second.
React (JSX)
import { useState } from "react"; function Clock() {  const [seconds, setSeconds] = useState(0);   setInterval(() => {    setSeconds((s) => s + 1);  }, 1000);   return <p>Seconds: {seconds}</p>;}
Output
Seconds: 0Seconds: 3Seconds: 10

32.2 Why is useEffect used?

  • Every state change runs the whole component function again, so every render creates a brand new interval.
  • After 1 second there is 1 interval, then 2, then 3, all adding to seconds together.
  • Work that touches the outside world (timer, API call, document.title, localStorage) is a side effect.
  • Render must stay pure, so React gives side effects their own place: useEffect.
Why a side effect in render is a bug
  1. 1.Render: setInterval creates interval #1

  2. 2.Interval calls setSeconds -> state changes

  3. 3.Re-render: setInterval creates interval #2

  4. 4.Re-render again: interval #3, all ticking together

  5. 5.Clock speeds up: 0, 3, 10...

A side effect inside render = bug

32.3 Your first useEffect

  • useEffect takes two things: a function containing the side effect, and a dependency array.
  • React runs the function after render and commit; on page load the tab title becomes Cart (0).
  • On click, setCount makes count 1 and React re-renders; React sees count changed in the deps, so the effect runs again: Cart (1), then Cart (2).
React (JSX)
import { useState, useEffect } from "react"; function Cart() {  const [count, setCount] = useState(0);   useEffect(() => {    document.title = `Cart (${count})`;  }, [count]);   const add = () => setCount(count + 1);   return <button onClick={add}>Add</button>;}
Output
Tab title: Cart (0)-- click Add --Tab title: Cart (1)-- click Add --Tab title: Cart (2)
useEffect lifecycle
  1. 1.Render: component returns JSX

  2. 2.Commit: DOM updated, browser paints

  3. 3.Effect runs (setup)

  4. 4.State/prop in deps changes -> re-render

  5. 5.Cleanup of previous effect runs, then the new effect runs

  6. 6.Unmount: final cleanup runs

Effects run after commit, never during render

32.4 The 3 modes of the dependency array

Dependency arrayWhen the effect runsExample
No arrayAfter every renderRarely what you want
[] (empty)Only once on mount (component first appears)Start a timer / connection once
[count]On mount and whenever count changesSync document.title with count

32.5 useEffect cleanup

  • Move setInterval inside useEffect with an empty array: the interval is created only once on mount.
  • Return a function from the effect that calls clearInterval: this is the cleanup function.
  • React runs the cleanup on unmount and before the effect runs again.
  • Now the clock correctly goes 1, 2, 3.
React (JSX)
import { useState, useEffect } from "react"; function Clock() {  const [seconds, setSeconds] = useState(0);   useEffect(() => {    const id = setInterval(() => {      setSeconds((s) => s + 1);    }, 1000);    return () => clearInterval(id);  }, []);   return <p>Seconds: {seconds}</p>;}
Output
Seconds: 0Seconds: 1Seconds: 3

32.6 StrictMode double run

  • The Vite app is wrapped in StrictMode in main.jsx.
  • ChatRoom logs connect on mount and disconnect in the cleanup.
  • In development the console shows connect, disconnect, connect: StrictMode runs every effect through an extra setup + cleanup to test your cleanup.
  • In production the effect runs only once.
React (JSX)
import { useEffect } from "react"; function ChatRoom() {  useEffect(() => {    console.log("connect");    return () => console.log("disconnect");  }, []);   return <h1>Chat</h1>;}
Output
> connect> disconnect> connect

32.7 Common mistakes

  • Missing dependency: Greeting uses the name prop inside the effect but deps are []; when name changes from Rahul to Priya the heading updates but the title stays Hi Rahul.
  • Fix: put every prop or state used inside the effect into the dependency array.
React (JSX)
// Wrong: name is used but deps are empty -> title stays "Hi Rahul"function Greeting({ name }) {  useEffect(() => {    document.title = `Hi ${name}`;  }, []);   return <h1>Hi {name}</h1>;}
React (JSX)
// Right: name in the deps -> title becomes "Hi Priya"function Greeting({ name }) {  useEffect(() => {    document.title = `Hi ${name}`;  }, [name]);   return <h1>Hi {name}</h1>;}
  • Myth: "deps are your choice, add [] when you want it to run once". Every prop/state used in the effect must be listed; the ESLint react-hooks plugin (exhaustive-deps) warns about a missing one.
  • Myth: "the StrictMode double run is a bug". It is a development-only check that your cleanup is correct.
  • Starting a timer, listener or connection without a cleanup: it leaks and keeps running after unmount.

32.8 Best practices

  • Keep render pure; put timers, API calls and title updates only in useEffect.
  • List every value used in the effect in the dependency array.
  • If you start a timer, event listener or connection, always stop it in the cleanup.
  • One effect, one job: write a separate useEffect for a separate job.

32.9 Interview tips

  • useEffect is the hook that syncs a component with an external system; it runs after render and commit.
  • The dependency array decides when it runs again: none = every render, [] = mount only, [values] = when they change.
  • The cleanup stops the previous effect; it runs before the next effect and on unmount.
  • In development StrictMode runs effects twice so a missing cleanup gets caught; production runs once.