useEffect: dependencies and cleanup
How useEffect synchronises a component with systems outside React — when setup and cleanup run, how dependencies are compared, why Strict Mode runs effects twice — and how to avoid render loops, stale closures, fetch races and needless effects.
Reading level
Shows sections up to the selected level.
Before you start
This topic starts at Junior level.
What an Effect is for
React komponentində iki növ məntiq var. Render props və state-i JSX-ə çevirir və təmiz (pure) olmalıdır: eyni girişlər, eyni nəticə, heç bir yan təsir. Event handler-lər konkret qarşılıqlı əlaqəyə — klikə, formun göndərilməsinə — cavab kimi işləyir və dəyişikliklər məhz orada edilir. Bəzi işlər isə heç birinə uyğun gəlmir: onlar istifadəçi nəsə etdiyi üçün yox, komponent ekranda olduğu üçün baş verməlidir. Effekt məhz bunun üçündür. react.dev effektləri konkret event-in yox, "render-in özünün səbəb olduğu" yan təsirlər kimi tərif edir.
Effektin tipik işi xarici sistemlə sinxronlaşmaqdır, yəni React-in idarə etmədiyi bir şeylə:
- şəbəkə bağlantısı (chat otağı, WebSocket);
- brauzer API-ləri:
document.title,IntersectionObserver,windowüzərindəki listener; - taymerlər;
- React-dən kənar vidjet: xəritə, qrafik, video pleyer.
import { useEffect, useState } from "react";
function ChatRoom({ roomId }) {
const [messages, setMessages] = useState([]);
useEffect(() => {
const connection = createConnection(roomId);
connection.on("message", (m) => setMessages((list) => [...list, m]));
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <MessageList messages={messages} />;
}Effektin üç hissəsi var: setup (qoşulmaq), cleanup — setup-ın qaytardığı funksiya (ayrılmaq) — və asılılıqlar ([roomId]: otaq dəyişəndə yenidən qoşul). Bunu "mount zamanı işləyən kod" kimi yox, bir sinxronlaşmanı necə başlatmaq və necə dayandırmaq barədə təsvir kimi oxu. react.dev bunu belə ifadə edir: effekt yalnız nəyisə sinxronlaşdırmağa başlaya və sonra onu dayandıra bilər.
Effektə nə aid deyil
- Hesablamalar. Dəyəri props və state-dən hesablamaq olursa, onu render zamanı hesabla.
- İstifadəçi əməliyyatlarına reaksiya. Formu göndərmək, məhsul almaq, klikdən sonra bildiriş göstərmək — bunlar onlara səbəb olan event handler-ə aiddir.
react.dev-in sadə qaydası belədir: kodun niyə işlədiyini soruş. O, konkret qarşılıqlı əlaqə üzündən işləyirsə, bu, event-dir. İstifadəçi komponenti gördüyü üçün işləyirsə, effektdir.
Effektlər yalnız client-də işləyir, server render zamanı heç vaxt. Ona görə də yalnız brauzerdə olan API-lərə ehtiyacı olan kodun yeri effektlərdir.
A React component has two kinds of logic. Rendering turns props and state into JSX and must be pure: same inputs, same output, no side effects. Event handlers run in response to a specific interaction — a click, a submit — and are where things may change. Some work fits neither: it must happen because the component is on the screen, not because the user did something. That is what an Effect is for. react.dev defines Effects as side effects that are "caused by rendering itself, rather than by a particular event".
The typical job of an Effect is to synchronise with an external system, something React does not control:
- a network connection (a chat room, a WebSocket);
- browser APIs:
document.title, anIntersectionObserver, a listener onwindow; - timers;
- a non-React widget: a map, a chart, a video player.
import { useEffect, useState } from "react";
function ChatRoom({ roomId }) {
const [messages, setMessages] = useState([]);
useEffect(() => {
const connection = createConnection(roomId);
connection.on("message", (m) => setMessages((list) => [...list, m]));
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <MessageList messages={messages} />;
}The Effect has three parts: the setup (connect), the cleanup — the function the setup returns (disconnect) — and the dependencies ([roomId]: reconnect when the room changes). Read it as a description of how to start and how to stop one synchronisation, not as "code that runs on mount". react.dev puts it this way: an Effect can only start synchronising something and later stop synchronising it.
What does not belong in an Effect
- Calculations. If a value can be computed from props and state, compute it while rendering.
- Reactions to user actions. Submitting a form, buying a product, showing a toast after a click: these belong in the event handler that caused them.
react.dev's rule of thumb is to ask why the code runs. If it runs because of a particular interaction, it is an event. If it runs because the user sees the component, it is an Effect.
Effects run only on the client, never during server rendering. That also makes them the place for code that needs browser-only APIs.
When effects and cleanups run
React iki addımda işləyir: render (komponentini çağırıb JSX-i hesablamaq) və commit (dəyişiklikləri DOM-a tətbiq etmək). Effektlər commit-dən sonra işləyir:
render → commit (DOM updated) → browser paints → useEffect setupYenilənməyə qarşılıqlı əlaqə səbəb olmayıbsa, React adətən əvvəlcə brauzerə ekranı çəkməyə (paint) imkan verir, effekti isə ondan sonra işə salır, beləliklə effektlər istifadəçinin gördüyünü gecikdirmir. Yenilənməyə klik kimi qarşılıqlı əlaqə səbəb olubsa, React effekti paint-dən əvvəl də işə sala bilər. Hər iki halda effekt işləyəndə DOM artıq yenilənmiş olur.
Cleanup-ın vaxtı
Asılılıqların dəyişdiyi hər commit-dən sonra React əvvəlcə köhnə dəyərlərlə əvvəlki cleanup-ı, sonra yeni dəyərlərlə yeni setup-ı işə salır. Komponent silinəndə sonuncu cleanup son dəfə işləyir:
mount, roomId "general" setup: connect "general"
re-render, same roomId (nothing)
re-render, roomId "travel" cleanup: disconnect "general"
setup: connect "travel"
unmount cleanup: disconnect "travel"Hər render-in öz effekti var. İşləyən cleanup əvvəlki render zamanı yaradılıb, ona görə də o, həmin render-in roomId-si üzərində qurulmuş olur. Sənə lazım olan da məhz budur: qoşulduğun otaqdan ayrılırsan. Bir komponentin daxilində effektlər elan olunduqları sıra ilə işləyir, uşaq komponentin effektləri isə valideynin effektlərindən əvvəl işləyir.
Strict Mode: setup, cleanup, setup
Development rejimində Strict Mode ilk mount-dan dərhal sonra bir əlavə setup + cleanup dövrü işə salır, ona görə də connect → disconnect → connect görürsən. Bu, stress testdir. Cleanup setup-ı tam güzgüləyirsə, istifadəçi fərqi hiss etmir. Nəsə pozulursa — iki bağlantı, iki dəfə qeydə alınmış listener, iki dəfə işləyən taymer — deməli cleanup ya yoxdur, ya da natamamdır. Production-da setup bir dəfə işləyir.
Düzgün sual "effekti necə bir dəfə işə salım?" yox, "effektimi necə düzəldim ki, yenidən mount-dan sonra da işləsin?" sualıdır. Əlavə dövrü ref bayrağı ilə gizlətmə: react.dev xəbərdarlıq edir ki, bu, bug-ı düzəltmir, sadəcə gizlədir. Üstəlik, eyni unmount və yenidən mount istifadəçi ekrandan çıxıb geri qayıdanda real həyatda da baş verir.
React works in two steps: render (call your component and compute the JSX) and commit (apply the changes to the DOM). Effects run after the commit:
render → commit (DOM updated) → browser paints → useEffect setupIf the update was not caused by an interaction, React generally lets the browser paint first and runs the Effect afterwards, so effects don't delay what the user sees. If it was caused by an interaction such as a click, React may run the Effect before the paint. Either way, the DOM is already up to date when the Effect runs.
Cleanup timing
After every commit in which the dependencies changed, React first runs the previous cleanup with the old values, then the new setup with the new values. When the component is removed, the last cleanup runs one final time:
mount, roomId "general" setup: connect "general"
re-render, same roomId (nothing)
re-render, roomId "travel" cleanup: disconnect "general"
setup: connect "travel"
unmount cleanup: disconnect "travel"Each render has its own Effect. The cleanup that runs was created during the earlier render, so it is a over that render's roomId — which is exactly what you want: you disconnect from the room you connected to. Inside one component, effects run in the order they are declared, and a child's effects run before its parent's.
Strict Mode: setup, cleanup, setup
In development, Strict Mode runs one extra setup + cleanup cycle right after the first mount, so you see connect → disconnect → connect. It is a stress test. If the cleanup mirrors the setup, the user can't tell the difference. If something breaks — two connections, a listener registered twice, a timer firing twice — the cleanup is missing or incomplete. In production the setup runs once.
The right question is not "how do I run an Effect once?" but "how do I make my Effect work after remounting?". Don't hide the extra cycle with a ref flag: react.dev warns that this hides the bug instead of fixing it, and the same unmount and remount happens for real when the user leaves a screen and comes back.
The dependency array
useEffect(setup);
useEffect(setup, []);
useEffect(setup, [a, b]);- Array yoxdur: effekt hər commit-dən sonra işləyir.
[]: yalnız ilk commit-dən sonra işləyir, cleanup-ı isə unmount zamanı. Bu, yalnız effekt həqiqətən heç bir reaktiv dəyər oxumursa düzgündür.[a, b]: ilk commit-dən sonra vəavə yab-nin dəyişdiyi hər commit-dən sonra.
"Dəyişib" o deməkdir ki, asılılığı əvvəlki render-dəki dəyəri ilə müqayisə edəndə Object.is false qaytarıb. Sətir, ədəd və boolean üçün bu, adi dəyər bərabərliyidir (iki xırda istisna ilə: NaN NaN-a bərabərdir, 0 isə -0-dan fərqlənir). Obyekt, massiv və funksiyalar üçün isə bu, identiklikdir: eyni məzmunlu yeni obyekt dəyişmiş sayılır.
function SearchResults({ query, page }) {
const options = { query, page };
useEffect(() => {
loadResults(options);
}, [options]);
}options hər render-də yeni obyektdir, ona görə bu effekt hər render-dən sonra işləyir. Bunun əvəzinə primitivlərdən asılı ol ([query, page]) və obyekti effektin içində yarat.
Asılılıqları sən seçmirsən
Array effektin oxuduğu hər reaktiv dəyəri sadalamalıdır: props, state və komponentin gövdəsində onlardan hesablanan hər şey. react-hooks/exhaustive-deps lint qaydası bunu sənin yerinə yoxlayır.
useState-insetfunksiyası vəuseRef-in ref obyekti stabildir, onları yazmaya bilərsən.- Komponentdən kənarda elan olunmuş dəyərlər reaktiv deyil və siyahıya yazılmır.
ref.currentvə yalocation.pathnamekimi dəyişkən dəyərlər asılılıq ola bilməz: onların dəyişməsi render-ə səbəb olmur, ona görə React bunu heç vaxt hiss etməz.
Linter istəmədiyin asılılığı tələb edirsə, xəbərdarlığı susdurma — kodu elə dəyiş ki, effektə həmin dəyər lazım olmasın. Onu effektin içinə və ya komponentdən kənara köçür, state-i oxumaq əvəzinə updater funksiyadan (setCount((c) => c + 1)) istifadə et və ya dəyəri Effect Event vasitəsilə oxu. Stale closure bug-larının çoxu məhz susdurulmuş lint xəbərdarlığından başlayır.
useEffect(setup);
useEffect(setup, []);
useEffect(setup, [a, b]);- No array: the Effect runs after every commit.
[]: it runs after the first commit only, and its cleanup on unmount. That is correct only if the Effect really reads no reactive values.[a, b]: after the first commit and after every commit in whichaorbchanged.
"Changed" means that Object.is returned false when comparing a dependency with its value from the previous render. For strings, numbers and booleans that is ordinary value equality (with two quirks: NaN equals NaN, and 0 differs from -0). For objects, arrays and functions it is identity: a new object with the same contents counts as changed.
function SearchResults({ query, page }) {
const options = { query, page };
useEffect(() => {
loadResults(options);
}, [options]);
}options is a new object on every render, so this Effect runs after every render. Depend on the primitives instead ([query, page]) and create the object inside the Effect.
Dependencies are not a choice
The array must list every reactive value the Effect reads: props, state, and everything declared in the component body that is computed from them. The react-hooks/exhaustive-deps lint rule checks this for you.
- The
setfunction fromuseStateand the ref object fromuseRefare stable, so you may leave them out. - Values declared outside the component are not reactive and are not listed.
- Mutable values such as
ref.currentorlocation.pathnamecan't be dependencies: changing them doesn't cause a render, so React would never notice.
If the linter asks for a dependency you don't want, don't suppress the warning — change the code so the Effect doesn't need the value. Move it inside the Effect or outside the component, use an updater function (setCount((c) => c + 1)) instead of reading the state, or read the value through an Effect Event. A suppressed lint warning is how most stale-closure bugs start.
You might not need an Effect
Heç bir xarici sistem iştirak etmirsə, çox güman ki, effektə ehtiyacın yoxdur. Yalnız bir state-i digərinə görə düzəldən effektlər komponenti həm yavaşladır — hər commit-dən sonra əlavə render — həm də başa düşməyi çətinləşdirir. react.dev-in sadaladığı ən tipik hallar:
Törəmə dəyərlər: onları render zamanı hesabla.
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(firstName + " " + lastName);
}, [firstName, lastName]);İlk render köhnəlmiş fullName göstərir, sonra effekt state-i dəyişir və React yenidən render edir. const fullName = firstName + " " + lastName; daha qısadır, həmişə uyğundur və bir dəfə render olunur. Hesablama bahalıdırsa, onu effektə yox, useMemo-ya bük.
Prop dəyişəndə state-i sıfırlamaq: key istifadə et. <Profile key={userId} userId={userId} /> React-ə hər istifadəçinin profilini ayrı komponent kimi qəbul etdirir, ona görə də onun state-i "təmizləyən" effekt olmadan sıfırlanır.
İstifadəçi əməliyyatlarına reaksiya: event handler-dən istifadə et.
function BuyButton({ product }) {
function handleClick() {
addToCart(product);
showNotification(`Added ${product.name} to the cart`);
}
return <button onClick={handleClick}>Buy</button>;
}Səbəti izləyib bildiriş göstərən effekt səhifə yüklənəndə, yeniləndikdən sonra və ya səbət başqa səbəbdən dəyişəndə də işləyərdi. Bildirişin səbəbi klikdir, deməli onun yeri klik handler-idir.
Effekt zəncirləri, yəni yalnız başqa effektləri işə salmaq üçün state dəyişən effektlər: nəyi bacarırsansa render zamanı hesabla, növbəti state-in hamısını isə bir event handler-də təyin et.
Valideyni dəyişiklik barədə xəbərdar etmək: valideynin callback-ini state-i yeniləyən eyni event handler-də çağır və ya state-i yuxarı qaldır ki, sinxron saxlanmalı heç nə qalmasın.
Xarici store-a abunə olmaq: bunun üçün xüsusi hook var — useSyncExternalStore.
Geriyə real sinxronlaşmalar qalır: bağlantılar, abunəliklər, taymerlər, imperativ vidjetlər, "istifadəçi bu ekranı gördü" analitikası və data fetching (fetching bölməsindəki şərtlərlə). Komponenti review edəndə lazımsız effekti silmək çox vaxt elə onun bug-ının həllidir.
If no external system is involved, you probably don't need an Effect. Effects that only adjust state based on other state make a component slower — an extra render after each commit — and harder to follow. The most common cases react.dev lists:
Derived values: compute them during rendering.
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(firstName + " " + lastName);
}, [firstName, lastName]);The first render shows an outdated fullName, then the Effect sets state and React renders again. const fullName = firstName + " " + lastName; is shorter, always consistent, and renders once. If the calculation is expensive, wrap it in useMemo, not in an Effect.
Resetting state when a prop changes: use a key. <Profile key={userId} userId={userId} /> makes React treat each user's profile as a separate component, so its state resets without an Effect that "clears" it.
Reacting to user actions: use the event handler.
function BuyButton({ product }) {
function handleClick() {
addToCart(product);
showNotification(`Added ${product.name} to the cart`);
}
return <button onClick={handleClick}>Buy</button>;
}An Effect that watches the cart and shows the notification would also fire on page load, after a refresh, or when the cart changes for some other reason. The notification is caused by the click, so it belongs in the click handler.
Chains of Effects that set state only to trigger other Effects: compute what you can during rendering and set all the next state in one event handler.
Notifying a parent about a change: call the parent's callback in the same event handler that updates the state, or lift the state up so there is nothing to keep in sync.
Subscribing to an external store: useSyncExternalStore is the purpose-built hook.
What remains are real synchronisations: connections, subscriptions, timers, imperative widgets, analytics for "the user saw this screen", and data fetching (with the caveats in the fetching section). When you review a component, removing an unnecessary Effect is often the fix for its bug.
Infinite render loops
State dəyişən effekt yenidən render-ə səbəb olur. Bir dəfəlik bu, normaldır. Yenidən render effektin asılılıqlarını da dəyişəndə — və ya dependency array ümumiyyətlə olmayanda — bu, dövrə çevrilir:
useEffect(() => {
setCount(count + 1);
});react.dev bunu elektrik rozetkasını özünə qoşmağa bənzədir: effekt state-i dəyişir, render effekti yenidən işə salır, effekt yenə state-i dəyişir.
Bunun daha az nəzərə çarpan variantı da var: məhsul siyahısı item-ləri effektdə filtrləyir, filtr obyekti isə render zamanı yaradılır:
function ProductList({ products, status, sort }) {
const [visible, setVisible] = useState([]);
const filter = { status, sort };
useEffect(() => {
setVisible(applyFilter(products, filter));
}, [products, filter]);
return <Table rows={visible} />;
}Hər render yeni filter obyekti yaradır, ona görə Object.is asılılığın dəyişdiyini bildirir. Effekt işləyir və visible-a yeni massiv yazır; bu state dəyişikliyi render-ə səbəb olur, render isə daha bir filter yaradır. Boş dayanmalı olan səhifə durmadan commit edir. Development rejimində React belə xəbərdarlıq yazır: "Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render." Production build-i isə heç nə yazmır — səhifə sadəcə CPU yandırır.
Dövr üçün iki şərt lazımdır: effekt state-i yeniləyir və bu yeniləmə effektin asılılıqlarını dəyişir. Onlardan birini qır:
- Effektdən istifadə etmə.
visibletörəmə datadır: render zamanıconst visible = applyFilter(products, { status, sort });, bahalıdırsauseMemo-nun içində. Bu, əlavə render-i tamamilə aradan qaldırır. - Primitivlərdən asılı ol.
[products, status, sort]yaz və obyekti effektin içində qur. - Obyekti stabilləşdir: həqiqətən ötürülməlidirsə,
useMemo(() => ({ status, sort }), [status, sort]).
State-i eyni dəyərə (Object.is-ə görə) təyin etmək React-ə yeniləməni buraxmağa (bail out) imkan verir. Ona görə dövr formalı effektdə setReady(true) bir dövrədən sonra dayanır, setVisible([...]) isə heç vaxt dayanmır. Render-də yaradılan funksiya və massivlərlə, eləcə də valideynin hər render-də yenidən yaratdığı props ilə eyni tələyə düşməmək üçün diqqətli ol.
An Effect that sets state causes a re-render. Once, that is fine. It turns into a loop when the re-render also changes the Effect's dependencies — or when there is no dependency array at all:
useEffect(() => {
setCount(count + 1);
});react.dev compares this to plugging a power outlet into itself: the Effect sets state, the render runs the Effect again, the Effect sets state again.
A less obvious version: a product list filters its items in an Effect, and the filter object is created during rendering:
function ProductList({ products, status, sort }) {
const [visible, setVisible] = useState([]);
const filter = { status, sort };
useEffect(() => {
setVisible(applyFilter(products, filter));
}, [products, filter]);
return <Table rows={visible} />;
}Every render creates a new filter object, so Object.is reports a changed dependency. The Effect runs and stores a new array in visible; that state change causes a render, which creates another filter. The page keeps committing while it should be idle. In development React logs "Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render." The production build logs nothing — the page just burns CPU.
A loop needs two things: the Effect updates state, and that update changes the Effect's dependencies. Break either:
- Don't use an Effect.
visibleis derived data:const visible = applyFilter(products, { status, sort });during rendering, insideuseMemoif it is expensive. This removes the extra render entirely. - Depend on primitives. List
[products, status, sort]and build the object inside the Effect. - Stabilise the object with
useMemo(() => ({ status, sort }), [status, sort])when it really has to be passed around.
Setting state to the same value (by Object.is) lets React bail out, which is why setReady(true) in a loop-shaped Effect stops after one round while setVisible([...]) never does. Watch for the same trap with functions and arrays created in render, and with props that a parent recreates on every render.
Stale closures in Effects
Hər render yeni props və state sabitləri yaradır, həmin render-də yaradılan effekt isə onlar üzərində olur. Effekt yeni render-lərdən sonra da işləyən funksiya qoyub gedirsə — interval, abunəlik callback-i — həmin funksiya köhnə dəyərləri görməyə davam edir. Buna deyilir.
Qaralamanı bir neçə saniyədən bir saxlayan redaktora bax:
function Editor({ docId }) {
const [text, setText] = useState("");
useEffect(() => {
const id = setInterval(() => {
saveDraft(docId, text);
}, 3000);
return () => clearInterval(id);
}, []);
return <textarea value={text} onChange={(e) => setText(e.target.value)} />;
}Effekt bir dəfə işləyir, ona görə də interval callback-i text-in "" olduğu ilk render-ə aiddir. İstifadəçi yazır və yeni mətni görür, tətbiq isə hər üç saniyədən bir boş ilk versiyanı saxlayır. Səhifə yenidən yüklənəndən sonra düzəlişlər yoxa çıxır. Linter docId və text-i çatışmayan asılılıq kimi göstərərdi: buradakı [] əslində gizlədilmiş susdurmadır.
Həll yolları, ən birbaşasından başlayaraq:
- Asılılıqları yaz:
[docId, text]. Interval hər dəyişiklikdən sonra təzə closure ilə yenidən yaradılır və eyni anda yenə yalnız bir taymer olur. Autosave üçün bu, həm də "son düymə basışından üç saniyə sonra saxla" deməkdir, yəni — bunu interval yox,setTimeoutdaha aydın ifadə edir. - Son dəyəri ref-dən oxu. Ref bütün render-lərin bölüşdüyü bir dəyişkən qutudur:
const textRef = useRef(text);
useEffect(() => {
textRef.current = text;
}, [text]);
useEffect(() => {
const id = setInterval(() => saveDraft(docId, textRef.current), 3000);
return () => clearInterval(id);
}, [docId]);Ref-i render zamanı yox, effektdə və ya event handler-də yenilə.
useEffectEvent(React 19.2-dən stabildir): "cari mətni saxla" məntiqini Effect Event-ə köçür; o, asılılıq olmadan həmişə son props və state-i görür. Aşağıdakı senior bölməsinə bax.
Updater funksiya (setCount((c) => c + 1)) stale closure-u yalnız callback state-i əvvəlki dəyərinə görə yazmalı olanda həll edir. Autosave isə cari dəyəri oxuyub başqa yerə göndərməlidir, ona görə ona yuxarıdakı həllərdən biri lazımdır.
Every render creates new props and state constants, and an Effect created in that render is a over them. If the Effect leaves a function running after newer renders — an interval, a subscription callback — that function keeps seeing the old values. That is a .
Take an editor that saves the draft every few seconds:
function Editor({ docId }) {
const [text, setText] = useState("");
useEffect(() => {
const id = setInterval(() => {
saveDraft(docId, text);
}, 3000);
return () => clearInterval(id);
}, []);
return <textarea value={text} onChange={(e) => setText(e.target.value)} />;
}The Effect runs once, so its interval callback belongs to the first render, where text is "". The user types and sees the new text, while every three seconds the app saves the empty first version. After a reload the edits are gone. The linter would have reported docId and text as missing dependencies: [] here is a suppression in disguise.
Fixes, from the most direct:
- List the dependencies:
[docId, text]. The interval is recreated with a fresh closure after each change, and there is still only one timer at a time. For autosave this also means "save three seconds after the last keystroke", a — asetTimeoutexpresses that more clearly than an interval. - Read the latest value from a ref. A ref is one mutable box shared by all renders:
const textRef = useRef(text);
useEffect(() => {
textRef.current = text;
}, [text]);
useEffect(() => {
const id = setInterval(() => saveDraft(docId, textRef.current), 3000);
return () => clearInterval(id);
}, [docId]);Update the ref in an Effect or an event handler, not during rendering.
useEffectEvent(stable since React 19.2): put "save the current text" in an Effect Event, which always sees the latest props and state without being a dependency. See the senior section below.
An updater function (setCount((c) => c + 1)) fixes a stale closure only when the callback needs to write state based on its previous value. Autosave needs to read the current value and send it somewhere else, so it needs one of the fixes above.
Data fetching and race conditions
Effektdə data fetch etmək olar, amma sadəlövh variantda klassik bug var — cavablar sorğuların göndərildiyi sıradan fərqli sırada gələ bilər:
useEffect(() => {
fetchResults(query).then((json) => setResults(json));
}, [query]);Əvvəl "re", sonra "react" yaz: iki sorğu gedir. "re" cavabı daha yavaşdırsa, o, sonuncu gəlir və "react" nəticələrinin üzərinə yazılır; ekranda istifadəçinin artıq axtarmadığı sorğunun nəticələri görünür.
react.dev-in göstərdiyi həll köhnə sorğunu köhnəlmiş kimi işarələyən cleanup-dır:
useEffect(() => {
let ignore = false;
fetchResults(query).then((json) => {
if (!ignore) setResults(json);
});
return () => {
ignore = true;
};
}, [query]);query dəyişəndə React növbəti setup-dan əvvəl əvvəlki cleanup-ı işə salır, ona görə əvvəlki effektin ignore-u true olur və onun gecikmiş cavabı atılır. Hər effektin öz ignore-u var — cleanup öz render-inin dəyişəni üzərində closure-dur — ona görə yalnız sonuncu sorğunun cavabı istifadə olunur.
Sorğunun özünü də ləğv edə bilərsən:
useEffect(() => {
const controller = new AbortController();
fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal })
.then((response) => response.json())
.then((json) => setResults(json))
.catch((error) => {
if (error.name !== "AbortError") setError(error);
});
return () => controller.abort();
}, [query]);Abort etmək trafikə də qənaət edir; ləğv olunmuş fetch AbortError ilə reject olur və sən onu nəzərə almırsan. Development-də Strict Mode ilk sorğunu başladıb dərhal ləğv edir — bu, gözləniləndir, production-da isə bir sorğu gedir.
Data qatı bunu niyə daha yaxşı edir
Effektdəki fetch keşləmir, komponentlər arasında eyni sorğuları birləşdirmir (dedup etmir), yalnız render-dən sonra başlayır (yəni iç-içə komponentlər şəlalə kimi bir-birinin ardınca fetch edir) və serverdə işləmir. react.dev framework-ün daxili data fetching mexanizmini və ya TanStack Query, SWR, React Router kimi client tərəf keşini tövsiyə edir. ignore şablonu yenə də vacibdir: o alətlər məhz bunu sənin yerinə edir, bu sual isə müsahibələrdə standartdır.
Fetching in an Effect is allowed, but the naive version has a classic bug — responses can arrive in a different order than the requests were sent:
useEffect(() => {
fetchResults(query).then((json) => setResults(json));
}, [query]);Type "re", then "react": two requests go out. If the "re" response is slower, it arrives last and overwrites the results for "react", and the screen shows results for a query the user no longer has.
The fix react.dev shows is a cleanup that marks the old request as stale:
useEffect(() => {
let ignore = false;
fetchResults(query).then((json) => {
if (!ignore) setResults(json);
});
return () => {
ignore = true;
};
}, [query]);When query changes, React runs the previous cleanup before the next setup, so the previous Effect's ignore becomes true and its late response is dropped. Each Effect has its own ignore — the cleanup is a closure over its render's variable — so only the latest query's response is used.
You can also cancel the request itself:
useEffect(() => {
const controller = new AbortController();
fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal })
.then((response) => response.json())
.then((json) => setResults(json))
.catch((error) => {
if (error.name !== "AbortError") setError(error);
});
return () => controller.abort();
}, [query]);Aborting also saves bandwidth; an aborted fetch rejects with an AbortError, which you ignore. In development, Strict Mode starts the first request and aborts it immediately — expected, since production sends one request.
Why a data layer does this better
A fetch in an Effect doesn't cache, doesn't deduplicate requests between components, starts only after rendering (so nested components fetch in a waterfall) and doesn't run on the server. react.dev recommends the built-in data fetching of a framework, or a client-side cache such as TanStack Query, SWR or React Router. The ignore pattern still matters: it is what those tools do for you, and it is a standard interview question.
useLayoutEffect and useEffectEvent
useLayoutEffect
useLayoutEffect-in imzası useEffect ilə eynidir, amma o, brauzer ekranı yenidən çəkməzdən əvvəl işləyir. React zəmanət verir ki, onun kodu və ondan planlaşdırılan hər state yeniləməsi paint-dən əvvəl emal olunacaq. Buna görə o, layout-u ölçüb istifadəçi səhv variantı görməmiş düzəltmək üçün alətdir:
function Tooltip({ anchorTop, children }) {
const ref = useRef(null);
const [height, setHeight] = useState(0);
useLayoutEffect(() => {
setHeight(ref.current.getBoundingClientRect().height);
}, []);
const top = anchorTop - height < 0 ? anchorTop + 24 : anchorTop - height;
return <div ref={ref} style={{ position: "absolute", top }}>{children}</div>;
}useEffect ilə brauzer tooltip-i səhv yerdə çəkib bir kadr sonra yerini dəyişə bilərdi: gözə çarpan titrəmə (flicker). Bunun qiyməti var: layout effektləri paint-i bloklayır, onların içindəki state yeniləməsi isə React-i qalan bütün effektləri, useEffect-lər də daxil olmaqla, dərhal işə salmağa məcbur edir. useEffect-ə üstünlük ver, useLayoutEffect-ə isə yalnız ölçünü paint-dən əvvəl tətbiq etmək mütləq lazım olanda müraciət et. Layout effektləri server render zamanı da işləmir, ona görə server HTML-i həmişə ilk, ölçülməmiş keçiddir.
useEffectEvent
Bəzən effekt dəyəri oxumalı, amma ona reaksiya verməməlidir. Chat otağı roomId dəyişəndə yenidən qoşulmalıdır, theme dəyişəndə isə yox, halbuki "qoşuldu" bildirişi theme-dən istifadə edir:
import { useEffect, useEffectEvent } from "react";
function ChatRoom({ roomId, theme }) {
const onConnected = useEffectEvent(() => {
showNotification("Connected!", theme);
});
useEffect(() => {
const connection = createConnection(roomId);
connection.on("connected", () => onConnected());
connection.connect();
return () => connection.disconnect();
}, [roomId]);
}Effect Event həmişə son props və state-i görür və reaktiv deyil, ona görə heç vaxt dependency array-ə yazılmır. useEffectEvent React 19.2-də stabil API kimi çıxıb (cari buraxılış 19.3-dür); eslint-plugin-react-hooks-u yenilə ki, linter onu asılılıq kimi tələb etməsin. Qaydalar:
- onu yalnız eyni komponentin effektlərinin (və ya digər Effect Event-lərin) içindən çağır, render zamanı heç vaxt;
- başqa komponentlərə və hook-lara ötürmə — onun identikliyi qəsdən hər render-də dəyişir;
- effekti yenidən işə salmalı olan asılılıqları gizlətmək üçün istifadə etmə. O, mahiyyətcə effektdən göndərilən event olan məntiq üçündür: cari səbət ölçüsü ilə ziyarəti log etmək, cari temada bildiriş göstərmək, son mətni oxuyan autosave tiki.
useLayoutEffect
useLayoutEffect has the same signature as useEffect, but it fires before the browser repaints. React guarantees that its code, and any state update scheduled from it, is processed before the paint. That makes it the tool for measuring layout and correcting it before the user sees the wrong version:
function Tooltip({ anchorTop, children }) {
const ref = useRef(null);
const [height, setHeight] = useState(0);
useLayoutEffect(() => {
setHeight(ref.current.getBoundingClientRect().height);
}, []);
const top = anchorTop - height < 0 ? anchorTop + 24 : anchorTop - height;
return <div ref={ref} style={{ position: "absolute", top }}>{children}</div>;
}With useEffect the browser could paint the tooltip in the wrong place and move it a frame later: a visible flicker. The price is that layout effects block painting, and a state update inside one makes React run all remaining Effects immediately, useEffect ones included. Prefer useEffect, and reach for useLayoutEffect only when a measurement has to be applied before paint. Layout effects don't run during server rendering either, so the server HTML is always the first, unmeasured pass.
useEffectEvent
Sometimes an Effect must read a value without reacting to it. A chat room should reconnect when roomId changes, but not when theme changes, even though the "connected" notification uses theme:
import { useEffect, useEffectEvent } from "react";
function ChatRoom({ roomId, theme }) {
const onConnected = useEffectEvent(() => {
showNotification("Connected!", theme);
});
useEffect(() => {
const connection = createConnection(roomId);
connection.on("connected", () => onConnected());
connection.connect();
return () => connection.disconnect();
}, [roomId]);
}An Effect Event always sees the latest props and state, and it is not reactive, so it never goes into the dependency array. useEffectEvent shipped as a stable API in React 19.2 (the current release is 19.3); update eslint-plugin-react-hooks so the linter does not ask for it as a dependency. The rules:
- call it only from inside Effects (or other Effect Events) of the same component, never during rendering;
- don't pass it to other components or hooks — its identity changes on every render, by design;
- don't use it to hide dependencies that should re-run the Effect. It is for logic that is conceptually an event fired from an Effect: logging a visit with the current cart size, a notification in the current theme, an autosave tick that reads the latest text.
Interview tips
30 saniyəlik cavab. "useEffect komponenti React-dən kənardakı nəsə ilə sinxronlaşdırır. React setup-ı commit-dən sonra, adətən paint-dən sonra işə salır. Asılılıq dəyişəndə — Object.is ilə müqayisə olunur — əvvəlki cleanup-ı köhnə dəyərlərlə, sonra yeni setup-ı işə salır, sonuncu cleanup isə unmount zamanı işləyir. Development-də Strict Mode cleanup-ın setup-ı geri qaytardığını yoxlamaq üçün bir əlavə setup + cleanup dövrü əlavə edir. Bug-ların çoxu çatışmayan cleanup, stabil olmayan asılılıqlar və stale closure-lardır — bir çox effekt isə ümumiyyətlə olmamalıdır."
Gözlənilən suallar
- Render, commit, effekt və cleanup hansı ardıcıllıqla işləyir? Mount → update → unmount üçün zaman xəttini çək və cleanup-ın köhnə render-in dəyərlərini gördüyünü göstər.
- Effektim development-də niyə iki dəfə işləyir? Strict Mode. Cleanup-ı düzəlt, ref bayrağı əlavə etmə.
- Bu komponent niyə dövrə düşüb? Effekt state dəyişir və hər render-də yenidən yaradılan obyektdən, massivdən və ya funksiyadan asılıdır — ya da array-i yoxdur. Render zamanı hesabla, primitivlərdən asılı ol və ya memoizasiya et.
- Intervalım niyə köhnə state-i görür? Stale closure. Həllər: updater funksiya, düzgün asılılıqlar, ref,
useEffectEvent. - Effektdə təhlükəsiz fetch necə edilir? Cleanup-da
ignorebayrağı və yaAbortController; daha yaxşısı, framework loader-i və ya keş kitabxanası. useEffect, yoxsauseLayoutEffect? Adətən paint-dən sonra və paint-dən əvvəl. Layout effektləri paint-i bloklayır; onları ölçmələr üçün işlət.
Bal itirdən səhvlər
- Effektləri
componentDidMount/componentDidUpdatekimi izah etmək. Sinxronlaşmanın başlanması və dayandırılmasından danış; react.dev effektin baxış bucağından, hər dəfə bir başlat/dayandır dövrü ilə düşünməyi məsləhət görür. []-ı "bir dəfə işlət" deməyin üsulu saymaq. Boş array məqsəd yox, heç bir reaktiv dəyər oxumayan effektin nəticəsidir.- Kodu yenidən qurmaq əvəzinə
exhaustive-deps-i susdurmaq. - Törəmə state-i hesablamaq və ya klikə cavab vermək üçün effektdən istifadə etmək.
Senior səviyyəni göstərən məqamlar
Yalnız qaydaları yox, mühakiməni göstər: code review-da hansı effektləri silərdin, effekti komponentlərə aydın API verən custom hook-a (useOnlineStatus, useChatRoom) necə bükərdin və iş nə vaxt effektə yox, framework-ün data qatına aiddir. Bunu real nasazlıqlarla bağla: yalnız development log-larında görünən render dövrü, səssizcə köhnə mətni saxlayan autosave, köhnə sorğunun nəticələrini göstərən axtarış.
Platformadakı render-loop, autosave-stale-closure və search-race incident-ləri effektlərin debug edilməsini işləyən tətbiqdə məşq etməyə imkan verir.
A 30-second answer. "useEffect synchronises a component with something outside React. React runs the setup after the commit, usually after paint. When a dependency changes — compared with Object.is — it runs the previous cleanup with the old values and then the new setup, and the last cleanup runs on unmount. In development Strict Mode adds one setup + cleanup cycle to check that the cleanup undoes the setup. Most bugs are missing cleanups, unstable dependencies and stale closures — and many Effects shouldn't exist at all."
Questions you are likely to get
- What is the order of render, commit, effect and cleanup? Draw the timeline for mount → update → unmount, and point out that the cleanup sees the old render's values.
- Why does my Effect run twice in development? Strict Mode. Fix the cleanup; don't add a ref flag.
- Why is this component stuck in a loop? The Effect sets state and depends on an object, array or function recreated every render — or has no array. Derive during rendering, depend on primitives, or memoise.
- Why does my interval see old state? A stale closure. Fixes: an updater function, correct dependencies, a ref,
useEffectEvent. - How do you fetch safely in an Effect? An
ignoreflag orAbortControllerin the cleanup; better still, a framework loader or a cache library. useEffectoruseLayoutEffect? Usually after paint vs before paint. Layout effects block painting; use them for measurements.
Mistakes that cost points
- Explaining effects as
componentDidMount/componentDidUpdate. Talk about starting and stopping synchronisation; react.dev advises thinking from the Effect's perspective, one start/stop cycle at a time. - Treating
[]as a way to say "run once". An empty array is the result of an Effect that reads no reactive values, not a goal. - Suppressing
exhaustive-depsinstead of restructuring the code. - Using an Effect to compute derived state or to respond to a click.
Senior signal
Show judgement, not just rules: which Effects you would delete in a code review, how you would wrap an Effect in a custom hook (useOnlineStatus, useChatRoom) so components get a clear API, and when the work belongs to the framework's data layer instead of an Effect. Tie it to real failures: the render loop that only shows in development logs, the autosave that silently saved stale text, the search that showed results for an old query.
The platform's render-loop, autosave-stale-closure and search-race incidents let you practise debugging Effects in a running app.
What to check when reviewing Effects
Yazmadığın effekti — komanda yoldaşının, kitabxananın və ya AI assistentin kodunu — review edəndə bu siyahıdan istifadə et. Effekt bug-ları nadir hallarda dərhal görünür; onlar sonra təkrarlanan bağlantılar, render dövrləri və köhnə dəyərləri oxuyan callback-lər kimi üzə çıxır.
- Effekt React-dən kənardakı nə iləsə sinxronlaşırmı? Props və ya state-dən hesablanan dəyərlərin yeri render-dir, klikə və ya submit-ə reaksiyaların yeri isə event handler-dir. Yalnız bir state-i başqa state-dən təyin edən effekt köhnə data ilə əlavə render yaradır; çox vaxt düzəliş onu silməkdir.
- Hər setup-ın onu geri qaytaran cleanup-ı varmı? Bağlantılar kəsilməli, taymerlər təmizlənməli, listener-lər isə eyni funksiya referansı ilə silinməlidir. Development-də Strict Mode mount zamanı setup, cleanup, setup ardıcıllığını işə salır: təkrarlanan bağlantı və ya iki dəfə işləyən taymer cleanup-ın çatışmadığını göstərir; ikinci dövrü ötürən ref bayrağı bunu sadəcə gizlədir.
- Dependency array effektin oxuduğu hər reaktiv dəyəri sadalayırmı? Props, state və onlardan hesablanan dəyərlərin hamısı sayılır; susdurulmuş
react-hooks/exhaustive-depsxəbərdarlığı və ya onları buraxan[]interval və abunəliklərin köhnə render-in dəyərlərini oxumasına səbəb olur — bu, . - State dəyişən effekt render zamanı yaradılan obyektdən, massivdən və ya funksiyadan asılıdırmı? Hər render
Object.is-in dəyişmiş saydığı yeni referans gətirir, ona görə hər dəfə yeni obyekt və ya massiv yazan effekt, array-i olmayan effekt kimi, heç vaxt dayanmır. Development "Maximum update depth exceeded" yazır, production isə heç nə; bunun əvəzinə primitivlərdən asılı ol. - Fetch-in asılı olduğu dəyər dəyişəndə köhnə cavab atılır və ya ləğv olunurmu? Cavablar sorğuların göndərildiyi sıradan fərqli sırada gələ bilər: cleanup-da
ignorebayrağı və ya ləğv edilənAbortControlleryoxdursa, gecikmiş köhnə cavab yenisinin üzərinə yazılır.
Use this list when you review an Effect you did not write: a teammate's, a library's or an AI assistant's. Effect bugs rarely show at once; they surface later as duplicate connections, render loops and callbacks reading old values.
- Does the Effect synchronise with something outside React? Values computed from props or state belong in render, reactions to a click or submit in the event handler. An Effect that only sets state from other state adds a render with stale data; often the fix is to delete it.
- Does every setup have a cleanup that undoes it? Connections are closed, timers cleared, listeners removed with the same function reference. In development Strict Mode runs setup, cleanup, setup on mount: a duplicate connection or a timer firing twice means a missing cleanup; a ref flag skipping the second run only hides it.
- Does the dependency array list every reactive value the Effect reads? Props, state and values computed from them all count; a suppressed
react-hooks/exhaustive-depswarning or a[]that omits them leaves intervals and subscriptions reading an old render's values, a . - Does an Effect that sets state depend on an object, array or function created during render? Each render brings a new reference that
Object.istreats as changed, so an Effect storing a new object or array each time never stops, like one with no array. Development logs "Maximum update depth exceeded", production nothing; depend on primitives instead. - When a fetch's input changes, is the old response ignored or aborted? Responses can arrive out of order: without an
ignoreflag or anAbortControlleraborted in the cleanup, a slow older response overwrites the newer one.
Check your understanding
Practise this
Hands-on work that uses this topic.