Effect lifecycle

Effect 생명주기

When a dependency changes, React cleans up the previous synchronization before running the next effect.

···
html
<div class="scene"><div class="title">DEPENDENCY: <span id="dep">A</span></div><div class="lane"><span class="pill" id="connectA">connect A</span><span class="pill" id="cleanup">cleanup A</span><span class="pill" id="connectB">connect B</span></div><div class="wire"><span id="dot"></span></div><div class="label" id="note">A is subscribed</div></div>
css
.scene{width:min(94vw,800px);height:min(86vh,320px);position:relative;overflow:hidden;display:flex;flex-direction:column;justify-content:space-between;border:1px solid var(--line);border-radius:14px;background:var(--surface);padding:clamp(9px,2.4vmin,20px);font:500 clamp(15px,4vmin,18px)/1.3 var(--font-sans,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif)}.scene b,.scene strong{font-weight:700}.label{color:var(--muted)}.code{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}.pill{border:1px solid var(--line);border-radius:8px;padding:.4em .65em;background:var(--bg)}.active{border-color:var(--accent)!important;color:var(--accent)!important;background:color-mix(in srgb,var(--accent) 10%,var(--surface))!important}.title{font:700 clamp(12px,2.8vmin,17px) ui-monospace,monospace}.title span{color:var(--accent)}.lane{display:flex;justify-content:space-between;gap:5px;margin:clamp(15px,7vmin,48px) 0 15px}.lane .pill{flex:1;text-align:center}.wire{height:4px;background:var(--line);position:relative;margin:0 8% 18px}.wire span{position:absolute;top:-6px;width:16px;height:16px;border-radius:50%;background:var(--accent);left:0;transition:left .5s}.label{text-align:center}
js
const ids=["connectA","cleanup","connectB"];let n=0;function tick(){const step=n%3;ids.forEach((id,i)=>document.getElementById(id).classList.toggle("active",i===step));document.getElementById("dot").style.left=(step*50)+"%";document.getElementById("dep").textContent=step===2?"B":"A";document.getElementById("note").textContent=["A is subscribed","A is disconnected","B is subscribed"][step];n++}tick();setInterval(tick,950)

An effect synchronizes a component with an external system. React calls cleanup when dependencies change or the component unmounts.

The demo shows channel A disconnecting before B connects on a timeline. Do not copy values into state with an effect when they can be calculated during render.

When to use

Use it to synchronize subscriptions, sockets, timers, and other external resources.

Open as page ↗