Reconciliation and re-renders
What makes a React component render, how React compares element trees and decides what to keep, and how to stop needless re-renders — from keys and state position to memo, context, batching and the React Compiler.
Reading level
Shows sections up to the selected level.
Before you start
No prerequisites.
This topic starts at Junior level.
What a render is and what triggers it
React-də render React-in sənin komponentini çağırması deməkdir — nəyi göstərməli olduğunu öyrənmək üçün funksiyanı icra etməsi. Bu, səhifəni dəyişmək demək deyil: -a sonra və yalnız fərq olan yerlərdə toxunulur.
Komponent bu səbəblərdən biri ilə render olunur:
- İlk render —
createRoot(container).render(<App />)ilə başlayır. - Öz state-i dəyişib —
useState-insetfunksiyası və yauseReducer-indispatch-i render-i növbəyə qoyub. - Valideyni render olunub. Default olaraq komponent render olunanda React onun qaytardığı bütün komponentləri ən aşağıya qədər render edir — props-ları dəyişib-dəyişməməsindən asılı olmayaraq.
- Oxuduğu context dəyişib: ən yaxın provider fərqli
valuealanda həmin context-i oxuyan hər komponent render olunur.
"Props-u dəyişib" bu siyahıda yoxdur: props yalnız valideyn render olunduğu üçün dəyişir, bu da 3-cü səbəbdir.
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
console.log("render App", count);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
<Hint />
</>
);
}
function Hint() {
console.log("render Hint");
return <p>Press the button</p>;
}Hər klik yeni sayla render App, həm də render Hint çap edir. Hint-in props-u yoxdur və eyni mətni göstərir, amma valideyni render olunduğu üçün React onu yenidən çağırır. Sonra React nəticəni əvvəlki ilə müqayisə edir: düymənin mətni dəyişib, ona görə React həmin bir mətn node-unu yeniləyir; <p> isə eynidir, onun DOM node-una toxunulmur.
Bu niyə adətən problem deyil
Kiçik funksiyanı çağırmaq ucuzdur; baha olan DOM işi, layout və paint-dir. Eyni nəticə verən re-render heç bir DOM işi görmür. Re-render-lər ağacın yuxarısındakı komponent tez-tez yenilənəndə (hər hərfdə, scroll-da, taymerin hər tikində) və altındakı ağac böyük və ya ləng render olunanda problemə çevrilir. Mövzunun qalan hissəsi məhz bu barədədir.
Başlanğıc üçün iki vərdiş
- Render təmiz olmalıdır: eyni props, state və context xarici dəyişənləri və DOM-u dəyişmədən eyni nəticəni verməlidir. Development-də Strict Mode təmiz olmayan komponentləri üzə çıxarmaq üçün onları iki dəfə çağırır, ona görə render-dəki
console.logiki dəfə görünə bilər. - Düzəltməzdən əvvəl öyrən. React DevTools Profiler hansı komponentlərin və niyə render olunduğunu yazır, DevTools-un "Highlight updates when components render" ayarı isə render olunan hər komponenti işıqlandırır.
In React, rendering means React calling your component — running the function to find out what it should show. It is not the same as changing the page: the is touched only later, and only where something differs.
A component renders for one of these reasons:
- The initial render, started by
createRoot(container).render(<App />). - Its own state changed — a
setfunction fromuseStateordispatchfromuseReducerqueued a render. - Its parent rendered. By default, when a component renders, React renders every component it returns, all the way down — whether or not their props changed.
- A context it reads changed: every component that reads the context renders when the nearest provider gets a different
value.
"Its props changed" is not on the list: props only change because the parent rendered, which is reason 3.
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
console.log("render App", count);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
<Hint />
</>
);
}
function Hint() {
console.log("render Hint");
return <p>Press the button</p>;
}Each click logs render App with the new count and render Hint. Hint has no props and shows the same text, yet React calls it again because its parent rendered. Then React compares the result with the previous one: the button's text changed, so React updates that one text node; the <p> is identical, so its DOM node is left alone.
Why this is fine — usually
Calling a small function is cheap; DOM work, layout and paint are what cost. A re-render that produces the same output does no DOM work at all. Re-renders become a problem when a component high in the tree updates often (on every keystroke, scroll or timer tick) and the tree below it is large or slow to render. That is what the rest of this topic is about.
Two habits to start with
- Rendering must be pure: the same props, state and context should produce the same output, without changing outside variables or the DOM. In development, Strict Mode calls components twice to surface impure ones, so a
console.login render may appear twice. - Find out before you fix. The React DevTools Profiler records which components rendered and why, and the DevTools setting "Highlight updates when components render" flashes every component that renders.
Render and commit: elements are descriptions
react.dev-in təsvirinə görə ekranın hər yenilənməsi üç addımdan keçir: trigger (ilk render və ya state yeniləməsi), render (React komponentlərini çağırır) və commit (React DOM-u dəyişir). Commit-dən sonra brauzer ekranı çəkir.
Elementlər: UI-ı təsvir edən adi obyektlər
JSX funksiya çağırışlarına kompilyasiya olunur və onlar element qaytarır — təlimat yox, nəyin göstərilməli olduğunu deyən kiçik obyektlər:
const heading = <h1 className="title">Hello</h1>;
console.log(heading.type, heading.props);
// h1 { className: 'title', children: 'Hello' }
const profile = <Profile userId={7} />;
console.log(profile.type === Profile, profile.props);
// true { userId: 7 }Elementin type-ı ("h1" kimi teq adı və ya sənin komponent funksiyan), props-u və key-i var. <Profile userId={7} /> yaratmaq Profile-ı çağırmır; React onu sonra, render zamanı ağacda bu elementə rast gələndə çağırır.
Render: növbəti ağacı qurmaq
React yenilənməli olan komponenti çağırır, qaytardığı elementləri götürür, onların içindəki komponentləri çağırır və belə davam edir. Yeni elementləri əvvəlki dəfə render etdikləri ilə müqayisə edir — bu müqayisə reconciliation adlanır — və dəyişiklikləri müəyyənləşdirir: hansı DOM node-larını yaratmaq, hansı atributları və mətni yeniləmək, hansı node-ları silmək lazımdır. Nəyin render olunduğunu yadda saxlamaq, hər komponentin state-ini və hook-larını saxlamaq üçün React öz fiber ağacını (hər komponent nüsxəsi və ya host element üçün bir fiber) saxlayır.
Render zamanı hələ görünən heç nə baş vermir. React 18 və sonrakı versiyalarda React təcili olmayan render-i (transition) dayandıra və ya atıb yenidən başlaya bilər; bu da render-in təmiz olmalı olmasının daha bir səbəbidir.
Commit: minimal dəyişiklikləri tətbiq etmək
Commit zamanı React dəyişikliklər siyahısını DOM-a tətbiq edir, ref-ləri bağlayır və layout effektlərini icra edir; useEffect effektləri bundan sonra, adətən brauzer ekranı çəkəndən sonra işləyir. İlk render-də React bütün ağacı appendChild() ilə əlavə edir. Sonrakı render-lərdə isə React yalnız fərqlənən DOM node-larını dəyişir: react.dev-in nümunəsində saat hər saniyə <h1>-i yeniləyir, yanındakı <input> isə istifadəçinin yazdığını saxlayır, çünki React input-u heç vaxt əvəz etmir.
Zehni model
setState→ React həmin komponentin render-ini planlaşdırır.- Render → funksiyaların icra olunur və element qaytarır; React onları əvvəlki ağacla müqayisə edir.
- Commit → DOM-a yalnız fərqlər çatır; sonra brauzer layout və edir.
Platformadakı Mini React build layihəsində bu pipeline-ı özün yazırsan: createElement, DOM-a render, reconciliation və key-lər, funksional komponentlər, useState, batching və useEffect.
Every screen update goes through three steps, as react.dev describes them: trigger (the initial render or a state update), render (React calls your components) and commit (React changes the DOM). After the commit, the browser paints.
Elements: plain objects that describe the UI
JSX compiles to function calls that return elements — small objects that say what to show, not instructions:
const heading = <h1 className="title">Hello</h1>;
console.log(heading.type, heading.props);
// h1 { className: 'title', children: 'Hello' }
const profile = <Profile userId={7} />;
console.log(profile.type === Profile, profile.props);
// true { userId: 7 }An element has a type (a tag name like "h1" or your component function), props and a key. Creating <Profile userId={7} /> does not call Profile; React calls it later, during render, when it meets that element in the tree.
Render: build the next tree
React calls the component that needs to update, takes the elements it returns, calls the components inside them, and so on. It compares the new elements with what it rendered last time — this comparison is reconciliation — and works out the changes: which DOM nodes to create, which attributes or text to update and which nodes to remove. React keeps its own tree of fibers (one per component instance or host element) to remember what was rendered and to store each component's state and hooks.
During render nothing visible happens yet. In React 18 and later, React may pause or throw away a render that is not urgent (a transition) and start again; that is another reason render must be pure.
Commit: apply the minimal changes
In the commit, React applies the list of changes to the DOM, attaches refs and runs layout effects; useEffect effects run afterwards, usually once the browser has painted. On the first render it inserts the whole tree with appendChild(). On later renders, React only changes the DOM nodes that differ: react.dev's example is a clock that updates an <h1> every second while an <input> next to it keeps what the user typed, because React never replaced the input.
The mental model
setState→ React schedules a render of that component.- Render → your functions run and return elements; React diffs them against the previous tree.
- Commit → only the differences reach the DOM; then the browser does layout and .
The platform's Mini React build project has you write this pipeline yourself: createElement, rendering to the DOM, reconciliation and keys, function components, useState, batching and useEffect.
How React compares trees: type, position, key
İki ixtiyari ağacı optimal müqayisə etmək çox yavaşdır — ümumi alqoritmlər O(n³)-dür. React isə köhnə React sənədlərində açıq yazılmış iki fərziyyəyə əsaslanan O(n) evristikasından istifadə edir: fərqli tipli elementlər fərqli ağaclar yaradır, key-lər isə hansı uşaq elementlərin render-lər arasında eyni qaldığını React-ə bildirir.
Eyni mövqedə eyni tip: saxla və yenilə
Mövqedəki elementin type-ı əvvəlki dəfə ilə eynidirsə, React DOM node-unu və ya komponent nüsxəsini saxlayır və yalnız dəyişəni — atributları, mətni, props-u — yeniləyir. Komponent öz state-ini saxlayır.
function Scoreboard({ isFancy, isPaused }) {
if (isPaused) return <p>See you later!</p>;
return isFancy ? <Counter fancy /> : <Counter />;
}isFancy-ni dəyişmək Counter-in sayını saxlayır: hər iki budaqda o, eyni yerdə duran Counter-dir. React JSX sətirlərinə baxmır; vacib olan render olunmuş ağacdakı mövqedir, ona görə də if-in fərqli budaqlarındakı iki <Counter /> eyni slota düşürsə, "eyni sayğac" sayılır.
Fərqli tip: bütün alt ağacı yenidən mount et
isPaused true olanda slotda Counter yox, <p> olur. React Counter-i unmount edir (effektləri təmizlənir, state-i itir), onun DOM-unu silir və <p>-ni sıfırdan qurur. Geri keçəndə 0-dan başlayan təzə Counter mount olunur. Eyni şey bir səviyyə yuxarıda da baş verir: eyni Counter-i bir render-də <section>-a, növbətisində <div>-ə bükmək içindəki hər şeyi sıfırlayır, çünki valideynin tipi dəyişib.
Bunun izah etdiyi bug: komponent içində təyin olunan komponentlər
function SignupForm() {
const [email, setEmail] = useState("");
function EmailField() {
return <input value={email} onChange={(e) => setEmail(e.target.value)} />;
}
return <EmailField />;
}SignupForm-un hər render-i yeni EmailField funksiyası yaradır, ona görə də React eyni mövqedə fərqli tip görür və hər hərfdə input-u yenidən mount edir. Input hər hərfdən sonra fokusu itirir. Komponentləri modulun üst səviyyəsində elan et, heç vaxt başqa komponentin içində yox.
State-i key ilə qəsdən sıfırlamaq
key mövqenin bir hissəsinə çevrilir. Bunu render etmək
<Chat key={contact.id} contact={contact} />hər kontakta öz Chat-ini verir: kontakt dəyişəndə köhnəsi unmount, yenisi mount olunur, yarımçıq yazılmış mesaj səhv adama getmir. Key-lər yalnız qardaş elementlər arasında unikal olmalıdır, qlobal yox.
Comparing two arbitrary trees optimally is far too slow — general algorithms are O(n³). React instead uses a heuristic that is O(n), built on two assumptions the old React docs spelled out: elements of different types produce different trees, and keys tell React which children stay the same between renders.
Same type at the same position: keep and update
If the element at a position has the same type as last time, React keeps the DOM node or component instance and only updates what changed — attributes, text, props. A component keeps its state.
function Scoreboard({ isFancy, isPaused }) {
if (isPaused) return <p>See you later!</p>;
return isFancy ? <Counter fancy /> : <Counter />;
}Switching isFancy keeps the Counter's count: in both branches it is a Counter in the same place. React does not look at the JSX lines; what matters is the position in the rendered tree, so two <Counter /> tags in different branches of an if are "the same counter" if they end up in the same slot.
Different type: remount the whole subtree
When isPaused turns true, the slot holds a <p> instead of a Counter. React unmounts the Counter (its effects are cleaned up, its state is gone), removes its DOM, and builds the <p> from scratch. Switching back mounts a fresh Counter at 0. The same happens one level up: wrapping the same Counter in a <section> in one render and a <div> in the next resets everything inside, because the parent's type changed.
The bug this explains: components defined inside components
function SignupForm() {
const [email, setEmail] = useState("");
function EmailField() {
return <input value={email} onChange={(e) => setEmail(e.target.value)} />;
}
return <EmailField />;
}Every render of SignupForm creates a new EmailField function, so React sees a different type at the same position and remounts the input on every keystroke. The input loses focus after each letter. Declare components at the top level of the module, never inside another component.
Resetting state on purpose with key
A key becomes part of the position. Rendering
<Chat key={contact.id} contact={contact} />gives each contact its own Chat: switching contacts unmounts the old one and mounts a new one, so a half-typed message is not sent to the wrong person. Keys only have to be unique among siblings, not globally.
Keys in lists and the bugs of index keys
Siyahıda React yeni uşaq elementləri köhnələri ilə uyğunlaşdırmalıdır. Key olmasa, yalnız mövqeyə görə uyğunlaşdıra bilər: birinci uşağı birinci ilə və s. Sona əlavə etmək problem deyil, amma əvvələ əlavə edəndə hər mövqedə başqa element olur və React bütün uşaqları yeniləyir. Key-lər React-ə uşaqları kimliyə görə uyğunlaşdırmağa imkan verir: yeri dəyişən, əlavə olunan və ya silinən element öz DOM node-unu və state-ini saxlayır.
İndeks key-ləri state-i səhv elementə köçürür
function ShoppingList({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>
{item.name} <input placeholder="Note" />
</li>
))}
</ul>
);
}İstifadəçi Milk-in yanındakı qeydə "2 l" yazır. Sonra siyahının başına element əlavə olunur. key={index} ilə Eggs 0 key-ini alır — Milk-in key-ini — ona görə də React Milk-in <li>-ni və <input>-unu Eggs üçün istifadə edir: "2 l" qeydi artıq səhv elementin yanındadır, digər sətirlər də sürüşür. Sıralamadan və ya silmədən sonra da eyni şey olur. key={item.id} ilə React başda yeni key görür, bir yeni sətir yaradır və başqa heç nəyi yerindən oynatmır.
İndeks key-i yalnız siyahı heç vaxt sıralanmırsa, ortasına element əlavə və ya oradan silinmirsə və elementlərin öz state-i yoxdursa (idarə olunmayan input-lar və fokus da daxil) təhlükəsizdir. Key verməsən, React indeksdən istifadə edir və çatışmayan key barədə xəbərdarlıq edir.
Digər key səhvləri
- Render zamanı yaradılan key-lər —
map-in içindəkey={Math.random()}və yacrypto.randomUUID(). Key-lər render-lər arasında heç vaxt üst-üstə düşmür, ona görə React hər render-də bütün sətirləri və onların DOM-unu yenidən yaradır: yavaşdır və sətirlərdəki input itir. Id-ləri data render olunanda yox, yaradılanda yarat. - Qardaş elementlər arasında təkrarlanan key-lər: React xəbərdarlıq edir, yeniləmədə elementlər təkrarlana və ya itə bilər.
key-i prop kimi gözləmək. Komponentkey-i almır; id-ni ayrıca ötür:<Row key={id} id={id} />.- Key-i səhv elementə yazmaq: key
map-dən qaytarılan ən xarici elementə yazılır, onun içindəki nəyəsə yox.
Key-lər həm də alətdir
Dəyişən key "başqa element" demək olduğu üçün alt ağacı qəsdən sıfırlaya bilərsən: <Form key={user.id} /> state-i "sinxronlaşdıran" effekt olmadan hər istifadəçi üçün təzə forma açır.
For a list, React has to match the new children with the old ones. Without keys it can only match by position: the first child with the first child, and so on. Appending at the end is fine, but inserting at the start makes every position hold a different item, and React updates every child. Keys let React match children by identity instead, so a moved, inserted or removed item keeps its own DOM node and state.
Index keys move state to the wrong item
function ShoppingList({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>
{item.name} <input placeholder="Note" />
</li>
))}
</ul>
);
}The user types "2 l" into the note next to Milk. Then an item is added at the top. With key={index}, Eggs gets key 0 — the key that Milk had — so React reuses Milk's <li> and its <input> for Eggs: the note "2 l" is now next to the wrong item, and every other row shifts too. The same happens after sorting or deleting. With key={item.id}, React sees a new key at the front, creates one new row, and moves nothing else.
An index key is only safe when the list never reorders, never inserts or removes in the middle, and its items have no state of their own (including uncontrolled inputs and focus). React uses the index when you pass no key at all, and warns about the missing key.
Other key mistakes
- Keys generated during render —
key={Math.random()}orcrypto.randomUUID()inmap. The keys never match between renders, so React recreates every row and its DOM on each render: slow, and input in the rows is lost. Create ids when the data is created, not when it is rendered. - Duplicate keys among siblings: React warns, and items can be duplicated or dropped on update.
- Expecting
keyas a prop. A component does not receivekey; pass the id separately:<Row key={id} id={id} />. - Keys on the wrong element: the key belongs on the outermost element returned from
map, not on something inside it.
Keys are also a tool
Because a changed key means "a different item", you can reset a subtree deliberately: <Form key={user.id} /> starts a fresh form for each user, with no effect that "syncs" state.
Re-render cascades and how to stop them without memo
State yeniləməsi state-in sahibi olan komponenti və ondan aşağıdakı hər şeyi yenidən render edir. Həmin state ağacın yuxarısında yaşayırsa və tez-tez dəyişirsə, ardınca render-lər kaskadı gəlir. memo-ya əl atmazdan əvvəl strukturu düzəlt — react.dev də əvvəlcə bunları tövsiyə edir.
State-i aşağı köçür
Tutaq ki, foto səhifəsi şərh qutusunun mətnini öz state-ində, 200 fotoluq qalereyanın yanında saxlayır: hər hərf səhifəni və bütün qalereyanı yenidən render edir. Mətn yalnız textarea-ya lazımdır, ona görə ona ayrıca komponent ver:
function CommentBox() {
const [comment, setComment] = useState("");
return <textarea value={comment} onChange={(e) => setComment(e.target.value)} />;
}
function PhotoPage({ photos }) {
return (
<>
<PhotoGrid photos={photos} />
<CommentBox />
</>
);
}İndi yazmaq yalnız CommentBox-u yenidən render edir. PhotoGrid state sahibinin uşağı yox, qardaşıdır.
Məzmunu yuxarı qaldır: JSX-i children kimi ötür
Bəzən state məhz baha hissəni əhatə etməlidir — məqalənin ətrafında oxuma göstəricisi, formanın ətrafında modal:
function ReadingProgress({ children }) {
const [progress, setProgress] = useState(0);
return (
<div className="reader" onScroll={(e) => setProgress(scrolledShare(e.currentTarget))}>
<ProgressBar value={progress} />
{children}
</div>
);
}
function ArticlePage({ article }) {
return (
<ReadingProgress>
<Article article={article} />
</ReadingProgress>
);
}Scroll progress-i yeniləyir və ReadingProgress-i yenidən render edir, amma <Article />-i render olunmamış ArticlePage yaradıb. children əvvəlki dəfəki eyni element obyektidir, ona görə də React Article alt ağacını ötürür. State komponentə, məzmun isə onun valideyninə məxsusdur.
Baha işi əlaqəsiz render-lərdən kənarda saxla
Gövdəsində yüzlərlə elementi sıralayan və ya filtrləyən komponent bu işi hər state dəyişikliyində təkrarlayır — siyahı ilə heç bir əlaqəsi olmayan dəyişikliklərdə də, məsələn, yanındakı toggle və ya mətn sahəsi dəyişəndə. Həmin əlaqəsiz state-i ayrıca komponentə köçür (yenə state-i aşağı salmaq) və ya nəticəni cache-lə: useMemo(() => sortProducts(products, sortKey), [products, sortKey]) yalnız girişləri dəyişəndə yenidən sıralayır.
Yoxlama siyahısı
- Ən tez-tez hansı state dəyişir və onun sahibi hansı komponentdir?
- Bu state onu oxuyan yeganə hissənin yanında, daha aşağıda yaşaya bilərmi?
- Baha hissəni
childrenvə ya başqa JSX prop-u kimi ötürmək olarmı? - Render-də dəyişən şeydən asılı olmayan baha hesablama varmı?
Yalnız cavablar "yox" olanda — state həqiqətən yuxarıda lazımdır və uşaqlar bahadır — memoizasiya alətə çevrilir.
A state update re-renders the component that owns the state and everything below it. If that state lives high in the tree and changes often, a cascade of renders follows. Before reaching for memo, fix the structure — react.dev recommends these first.
Move state down
Say a photo page keeps the text of its comment box in its own state, next to a grid of 200 photos: every keystroke re-renders the page and the whole grid. Only the text area needs the text, so give it a component of its own:
function CommentBox() {
const [comment, setComment] = useState("");
return <textarea value={comment} onChange={(e) => setComment(e.target.value)} />;
}
function PhotoPage({ photos }) {
return (
<>
<PhotoGrid photos={photos} />
<CommentBox />
</>
);
}Now typing re-renders CommentBox alone. PhotoGrid is a sibling, not a child, of the state owner.
Lift content up: pass JSX as children
Sometimes the state has to wrap the expensive part — a reading-progress bar around an article, a modal around a form:
function ReadingProgress({ children }) {
const [progress, setProgress] = useState(0);
return (
<div className="reader" onScroll={(e) => setProgress(scrolledShare(e.currentTarget))}>
<ProgressBar value={progress} />
{children}
</div>
);
}
function ArticlePage({ article }) {
return (
<ReadingProgress>
<Article article={article} />
</ReadingProgress>
);
}Scrolling updates progress and re-renders ReadingProgress, but <Article /> was created by ArticlePage, which did not render. children is the same element object as last time, so React skips the Article subtree. The component owns the state; its parent owns the content.
Keep expensive work out of unrelated renders
A component that sorts or filters hundreds of items in its body repeats that work on every state change — also on changes that have nothing to do with the list, like a toggle or a text field next to it. Move that unrelated state into a component of its own (state down again), or cache the result: useMemo(() => sortProducts(products, sortKey), [products, sortKey]) sorts again only when its inputs change.
Checklist
- Which state changes most often, and which component owns it?
- Can that state live lower, next to the only part that reads it?
- Can the expensive part be passed in as
childrenor another JSX prop? - Is there expensive computation in render that does not depend on what changed?
Only when the answers are "no" — the state really is needed high up, and the children are expensive — does memoization become the tool.
memo, useMemo, useCallback — and when they are wasted
React-də girişlər eyni olanda əvvəlki nəticəni təkrar istifadə etmək deməkdir.
memo(Component)hər prop əvvəlki dəfə iləObject.ismüqayisəsinə görə bərabər olanda re-render-i ötürür.useMemo(fn, deps)hesablanmış dəyəri asılılıq dəyişənə qədər render-lər arasında cache-də saxlayır.useCallback(fn, deps)funksiyanı cache-də saxlayır; o,useMemo(() => fn, deps)-dir.
import { memo, useCallback, useMemo, useState } from "react";
const ProductRow = memo(function ProductRow({ product, onSelect }) {
return <li onClick={() => onSelect(product.id)}>{product.name}</li>;
});
function ProductList({ products, query }) {
const [selectedId, setSelectedId] = useState(null);
const visible = useMemo(
() => products.filter((product) => product.name.includes(query)),
[products, query],
);
const handleSelect = useCallback((id) => setSelectedId(id), []);
return (
<>
<p>Selected: {selectedId ?? "none"}</p>
<ul>
{visible.map((product) => (
<ProductRow key={product.id} product={product} onSelect={handleSelect} />
))}
</ul>
</>
);
}Məhsul seçmək ProductList-i yenidən render edir, amma heç bir sətir render olunmur: hər sətrin product-u və onSelect-i əvvəlki kimidir, filtr də yenidən işləmir, çünki products və query dəyişməyib. useCallback olmasaydı, onSelect hər render-də yeni funksiya olardı və bütün sətirlər onsuz da render olunardı.
Memoizasiya nə vaxt boşa gedir
- Hər render-də yeni olan props — inline
style={{ … }},onClick={() => …}, JSXchildren:memomüqayisə edir, fərq tapır və yenə render edir. - Ucuz komponentlər: props-u müqayisə etmək render qədər baha başa gələ bilər.
- Komponentin öz state-indən və ya context-dən gələn render-lər:
memoyalnız props-a baxır. - Sürətli hesablamalar: react.dev
console.timeilə ölçməyi və təxminən 1 ms-dən başlayaraq memoizasiya etməyi təklif edir. - Düzgünlük:
useMemozəmanət yox, performans ipucudur və React cache-i ata bilər. Səhv dependency array isə, məsələn,useCallback(fn, []), ilk render-in dəyərlərini dondurur — bu, -dur.
React Compiler
React Compiler 1.0 7 oktyabr 2025-dən stabildir: Rules of React-ə əməl edən və komponentləri və hook-ları avtomatik memoizasiya edən build-time alətdir (babel-plugin-react-compiler), hətta early return-dən sonra da — əl ilə yazılan hook-ları orada çağırmaq olmur. React 17 və sonrakı versiyaları dəstəkləyir (17 və 18 üçün react-compiler-runtime lazımdır); yalnız komponentlərin və hook-ların içində memoizasiya edir və cache-ləri komponentlər arasında bölüşmür.
Compiler ilə memo adətən lazım olmur. Yeni kodda ona güvən, useMemo/useCallback-i isə escape hatch kimi saxla, məsələn, effekt asılılığı olan dəyər üçün. Mövcud kodda react.dev əl ilə yazılmış memoizasiyanı yerində saxlamağı və ya silməzdən əvvəl diqqətlə test etməyi məsləhət görür, çünki bu, kompilyasiya nəticəsini dəyişə bilər.
in React means reusing a previous result when the inputs are the same.
memo(Component)skips re-rendering when every prop is equal to last time, compared withObject.is.useMemo(fn, deps)caches a computed value between renders until a dependency changes.useCallback(fn, deps)caches a function; it isuseMemo(() => fn, deps).
import { memo, useCallback, useMemo, useState } from "react";
const ProductRow = memo(function ProductRow({ product, onSelect }) {
return <li onClick={() => onSelect(product.id)}>{product.name}</li>;
});
function ProductList({ products, query }) {
const [selectedId, setSelectedId] = useState(null);
const visible = useMemo(
() => products.filter((product) => product.name.includes(query)),
[products, query],
);
const handleSelect = useCallback((id) => setSelectedId(id), []);
return (
<>
<p>Selected: {selectedId ?? "none"}</p>
<ul>
{visible.map((product) => (
<ProductRow key={product.id} product={product} onSelect={handleSelect} />
))}
</ul>
</>
);
}Selecting a product re-renders ProductList, but no row renders: each row's product and onSelect are the same as before, and the filter does not run again because products and query did not change. Without useCallback, onSelect would be a new function on every render and every row would render anyway.
When memoization is wasted
- Props that are new on every render — an inline
style={{ … }},onClick={() => …}, JSXchildren:memocompares, finds a difference and renders anyway. - Cheap components: comparing the props can cost as much as rendering.
- Renders from the component's own state or context:
memoonly looks at props. - Fast calculations: react.dev suggests measuring with
console.timeand memoizing from about 1 ms. - Correctness:
useMemois a performance hint, not a guarantee, and React may drop the cache. And a wrong dependency array, such asuseCallback(fn, []), freezes the first render's values — a .
React Compiler
React Compiler 1.0 is stable since October 7, 2025: a build-time tool (babel-plugin-react-compiler) that follows the Rules of React and memoizes components and hooks automatically, even after an early return, where manual hooks cannot be called. It supports React 17 and later (17 and 18 need react-compiler-runtime); it memoizes only inside components and hooks, and does not share caches between components.
With the compiler, memo is usually unnecessary. In new code, rely on it and keep useMemo/useCallback as escape hatches, for example for a value used as an effect dependency. In existing code, react.dev advises leaving manual memoization in place or testing carefully before removing it, since that can change the compiled output.
Context: why one change re-renders every consumer
Context dəyəri props olmadan provider-dən aşağıdakı hər komponentə ötürür. Performans qaydası qısadır: provider fərqli value alanda (Object.is-ə görə), həmin context-i oxuyan hər komponent provider-dən başlayaraq yenidən render olunur. memo bunu dayandırmır — o, yalnız props-u müqayisə edir.
Bir böyük context
Tutaq ki, dashboard paylaşdığı hər şeyi bir dəyərdə saxlayır: dil, bildirişlər siyahısı (yeniləri bir neçə saniyədən bir gəlir) və bildirişi bağlayan funksiya:
function AppProvider({ locale, children }) {
const [notifications, setNotifications] = useState([]);
const dismiss = (id) => setNotifications((list) => list.filter((n) => n.id !== id));
return (
<AppContext value={{ locale, notifications, dismiss }}>
{children}
</AppContext>
);
}valuehər render-də yeni obyektdir, ona görə də provider hər dəfə render olunanda bütün consumer-lər yenidən render olunur.- Onu
useMemo-ya bükəndə də hər yeni bildiriş dəyəri dəyişir və bütün consumer-lər yenidən render olunur — rəqəmləri formatlamaq üçün yalnız dilə ehtiyacı olan onlarla widget da daxil.
Birlikdə dəyişənlərə görə böl
function AppProvider({ locale, children }) {
const [notifications, setNotifications] = useState([]);
const dismiss = useCallback(
(id) => setNotifications((list) => list.filter((n) => n.id !== id)),
[],
);
return (
<LocaleContext value={locale}>
<NotificationActionsContext value={dismiss}>
<NotificationsContext value={notifications}>{children}</NotificationsContext>
</NotificationActionsContext>
</LocaleContext>
);
}
function RevenueWidget({ total }) {
const locale = useContext(LocaleContext);
return <p>{new Intl.NumberFormat(locale).format(total)}</p>;
}- Hər provider render-lər arasında sabit qalan dəyər alır: primitiv, state dəyəri və ya
useCallback-dən gələn funksiya. - Consumer-lər yalnız lazım olanı oxuyur.
RevenueWidgetyalnız dil dəyişəndə dəyişənLocaleContext-i oxuyur, ona görə də yeni bildiriş widget-ləri artıq yenidən render etmir. - Yalnız bir komponentə lazım olan state (mətn sahəsindəki qaralama) ümumiyyətlə context-ə aid deyil: onu həmin komponentdə saxla.
react.dev-in state üçün bir, dispatch üçün başqa context şablonu yaxşı başlanğıcdır; state-in hissələri fərqli tezliklə dəyişirsə, daha da böl.
Daha az seçmək
Context-in daxili selector-u yoxdur: consumer bir sahədən istifadə etsə də, dəyər dəyişəndə yenidən render olunur. Çoxlu komponent tez dəyişən datanın fərqli hissələrini oxuyursa, selector-lu store-dan istifadə et: useSyncExternalStore ilə oxunan store-lar (Zustand və Redux belə işləyir) komponenti yalnız onun seçdiyi hissə dəyişəndə yenidən render edir.
React 19-dan context birbaşa öz provider-i kimi render olunur (<LocaleContext value={locale}>), yuxarıdakı kodda olduğu kimi.
Context passes a value to every component below a provider without props. The performance rule is short: when a provider receives a different value (by Object.is), every component that reads that context re-renders, starting from the provider. memo does not stop it — it only compares props.
One big context
Say a dashboard shares everything through one value: the locale, the list of notifications (new ones arrive every few seconds) and a function to dismiss one:
function AppProvider({ locale, children }) {
const [notifications, setNotifications] = useState([]);
const dismiss = (id) => setNotifications((list) => list.filter((n) => n.id !== id));
return (
<AppContext value={{ locale, notifications, dismiss }}>
{children}
</AppContext>
);
}- The
valueis a new object on every render, so every consumer re-renders whenever the provider renders. - Even with
useMemoaround it, every new notification changes the value, and all consumers re-render — including dozens of widgets that only need the locale to format their numbers.
Split by what changes together
function AppProvider({ locale, children }) {
const [notifications, setNotifications] = useState([]);
const dismiss = useCallback(
(id) => setNotifications((list) => list.filter((n) => n.id !== id)),
[],
);
return (
<LocaleContext value={locale}>
<NotificationActionsContext value={dismiss}>
<NotificationsContext value={notifications}>{children}</NotificationsContext>
</NotificationActionsContext>
</LocaleContext>
);
}
function RevenueWidget({ total }) {
const locale = useContext(LocaleContext);
return <p>{new Intl.NumberFormat(locale).format(total)}</p>;
}- Each provider gets a value that is stable between renders: a primitive, a state value, or a function from
useCallback. - Consumers read only what they need.
RevenueWidgetreadsLocaleContext, which changes only when the language does, so a new notification no longer re-renders the widgets. - State that only one component needs (a draft in a text field) does not belong in context at all: keep it in that component.
react.dev's pattern of one context for state and one for dispatch is a good start; split further when parts of the state change at different rates.
Selecting less
Context has no built-in selector: a consumer re-renders when the value changes, even if it uses one field. When many components read different slices of fast-changing data, use a store with selectors: stores read through useSyncExternalStore (Zustand and Redux work this way) re-render a component only when its selected slice changes.
Since React 19 a context is rendered directly as its provider (<LocaleContext value={locale}>), as in the code above.
Batching and what happens inside setState
set funksiyası əlindəki dəyişəni dəyişmir — o, yeniləməni növbəyə qoyur və React-dən yenidən render etməyi xahiş edir. Cari render-in count-u növbəti render-ə qədər eyni qalır; react.dev state-i snapshot adlandırır.
Avtomatik batching
React event handler-dəki bütün kod icra olunana qədər gözləyir, sonra bütün yeniləmələr üçün bir dəfə render edir — bu, -dir. React 18-dən (createRoot ilə) yeniləmələr hər yerdə batch olunur: event handler-lərdə, timeout-larda, promise callback-lərində və native event listener-lərində. React 18-dən əvvəl yalnız React event handler-lərinin içindəki yeniləmələr batch olunurdu. React ayrı-ayrı qəsdən edilən hadisələri birləşdirmir: hər klik ayrıca emal olunur.
Yeniləmə növbəsi
function handleClick() {
setNumber(number + 5);
setNumber((n) => n + 1);
console.log(number);
}Bu render-də number 0-dır. Növbədə "5 ilə əvəz et", sonra n => n + 1 var. Handler 0 çap edir, növbəti render-də isə React növbəni ardıcıllıqla emal edir: 5, sonra 6. Adi dəyər özündən əvvəl növbəyə qoyulanları əvəz edir; updater funksiya isə əvvəlki yeniləmənin nəticəsini alır. Buna görə də setCount(c => c + 1) üç dəfə 3 əlavə edir, setCount(count + 1) üç dəfə isə 1.
Yeni dəyər cari state ilə eynidirsə (Object.is), React komponenti və onun uşaqlarını yenidən render etmir. Bəzən uşaqları ötürməzdən əvvəl komponenti bir dəfə çağırmalı olur; bu, gözlənilən davranışdır.
İmtina: flushSync
Nadir hallarda DOM-un dərhal yenilənməsi lazımdır, məsələn, yeni elementə scroll etmək üçün:
import { flushSync } from "react-dom";
function handleAdd(todo) {
flushSync(() => {
setTodos((list) => [...list, todo]);
});
listRef.current.lastChild.scrollIntoView();
}flushSync callback-in içindəki yeniləməni sinxron render və commit edir. O, bahadır və main thread-i bloklayır — yalnız belə hallarda istifadə et.
React-in içində
Platformadakı "React: useState necə işləyir" (react-use-state, React v19.3.0) source tour-u bunu React-in kodu boyunca izləyir: useState cari dispatcher-dən soruşur, renderer isə onu mount və update arasında dəyişir; hər komponentin hook-ları onun fiber-indəki linked list-dir və çağırış sırasına görə tapılır (Rules of Hooks-un səbəbi budur); set çağırışı update yaradır, Object.is ilə erkən bailout edə bilər, onu hook-un update queue-suna əlavə edir, fiber-i və valideynlərini prioritet lane-i ilə işarələyir və neçə yeniləmə gəlməsindən asılı olmayaraq bir render planlaşdırır. Növbəti render növbəni ardıcıllıqla təkrar emal edir. Eyni ideyanın minimal versiyası yeniləmələri toplayır və onları bir birlikdə emal edir.
A set function does not change the variable you are holding — it queues an update and asks React to render again. The current render's count stays the same until the next render; react.dev calls state a snapshot.
Automatic batching
React waits until all code in the event handler has run, then renders once for all the updates — this is . Since React 18 (with createRoot), updates are batched everywhere: in event handlers, timeouts, promise callbacks and native event listeners. Before React 18, only updates inside React event handlers were batched. React does not batch across separate intentional events: each click is handled on its own.
The update queue
function handleClick() {
setNumber(number + 5);
setNumber((n) => n + 1);
console.log(number);
}number is 0 in this render. The queue holds "replace with 5", then n => n + 1. The handler logs 0, and on the next render React processes the queue in order: 5, then 6. A plain value replaces whatever was queued before it; an updater function receives the result of the previous update. That is why setCount(c => c + 1) three times adds 3, while setCount(count + 1) three times adds 1.
If the new value is the same as the current state (Object.is), React skips re-rendering the component and its children. Sometimes it still has to call the component once before it can skip the children; that is expected.
Opting out: flushSync
Rarely you need the DOM updated right away, for example to scroll to a new item:
import { flushSync } from "react-dom";
function handleAdd(todo) {
flushSync(() => {
setTodos((list) => [...list, todo]);
});
listRef.current.lastChild.scrollIntoView();
}flushSync renders and commits the update inside the callback synchronously. It is expensive and blocks the main thread — use it only for cases like this.
Inside React
The platform's source tour "React: how useState works" (react-use-state, React v19.3.0) follows this through React's code: useState asks the current dispatcher, which the renderer switches between mount and update; each component's hooks are a linked list on its fiber, found by call order (the reason for the Rules of Hooks); a set call creates an update, may bail out early with Object.is, appends it to the hook's update queue, marks the fiber and its parents with a priority lane, and schedules one render for however many updates came in. The next render replays the queue in order. A minimal version of the same idea collects updates and flushes them together in one .
Interview tips
30 saniyəlik cavab. "Render React-in element — UI-ın təsviri — almaq üçün komponentlərini çağırmasıdır. Komponent mount olanda, state-i dəyişəndə, valideyni render olunanda və ya oxuduğu context dəyişəndə render olunur. React yeni elementləri əvvəlki ağacla müqayisə edir — eyni mövqedə eyni tip state-i saxlayır, fərqli tip yenidən mount olunur, key-lər siyahı elementlərini tanıdır — və DOM-a yalnız fərqləri commit edir."
Gözlənilən suallar
- Re-render DOM-u yeniləyirmi? Xeyr: render komponentləri çağırır, commit olunan yalnız fərqlərdir.
- Key-lər niyə vacibdir? Niyə indeks yox? Kimliyə görə və mövqeyə görə uyğunlaşdırma; input-un səhv sətrə keçməsini göstər.
- Bu state niyə sıfırlandı? Eyni mövqedə fərqli tip, dəyişən sarğı element, başqa komponentin içində təyin olunan komponent və ya dəyişən key.
- Səhifə yazarkən ləngiyir — nə edirsən? Əvvəlcə profil çıxar. Sonra state-i aşağı köçür, məzmunu
childrenkimi ötür, sabit props ilə memoizasiya et, context-i böl, React Compiler-i nəzərdən keçir. Məşq üçün platformadakı çağırışları qeyd et:perf-typing-lag,perf-slow-filter,perf-context-storm. - Bu handler neçə render-ə səbəb olur? Batching: hər hadisəyə bir render, React 18-dən timeout-larda və promise-lərdə də; updater funksiyalar və adi dəyərlər.
Bal itirdən səhvlər
- "React props dəyişəndə komponenti yenidən render edir" demək. O, valideyn render olunanda yenidən render edir; dəyişən props bunun nəticəsidir.
- "Re-render DOM-u yenidən yaratmaq deməkdir" demək.
- "Hər ehtimala qarşı" hər şeyi
memo/useMemo-ya bükmək və yamemo-nun context yeniləmələrini blokladığını düşünmək. - Dəyişən siyahı üçün key kimi
Math.random()-dan və ya indeksdən istifadə etmək. - React-in "virtual DOM-u real DOM ilə" müqayisə etdiyini demək. O, yeni elementləri canlı DOM ilə yox, özünün əvvəlki ağacı (fiber-lər) ilə müqayisə edir.
Senior səviyyəni göstərən məqamlar
Trade-off-ları profildən götürülmüş rəqəmlərlə izah et; struktur düzəlişlərinin (state-i aşağı salmaq, children) niyə memoizasiyadan əvvəl gəldiyini, React Compiler-in bu tövsiyəni necə dəyişdiyini və state-in fiber-lərdə yeniləmələr növbəsi kimi necə yaşadığını bil.
A 30-second answer. "Rendering is React calling your components to get elements — descriptions of the UI. A component renders on mount, when its state changes, when its parent renders, or when a context it reads changes. React diffs the new elements against the previous tree — same type at the same position keeps state, a different type remounts, keys identify list items — and commits only the differences to the DOM."
Questions you are likely to get
- Does a re-render update the DOM? No: rendering calls components; only differences are committed.
- Why do keys matter? Why not the index? Matching by identity vs position; show the input moving to the wrong row.
- Why did this state reset? A different type at the same position, a changed wrapper, a component defined inside another, or a changed key.
- This page lags while typing — what do you do? Profile first. Then move state down, pass content as
children, memoize with stable props, split context, and consider the React Compiler. Mention the platform's challenges as practice:perf-typing-lag,perf-slow-filter,perf-context-storm. - How many renders does this handler cause? Batching: one per event, in timeouts and promises too since React 18; updater functions vs plain values.
Mistakes that cost points
- Saying "React re-renders a component when its props change". It re-renders when the parent renders; changed props are a consequence.
- Saying "re-rendering means re-creating the DOM".
- Wrapping everything in
memo/useMemo"to be safe", or believingmemoblocks context updates. - Using
Math.random()or the index as a key for a list that changes. - Saying React diffs "the virtual DOM against the real DOM". It compares the new elements with its previous tree (fibers), not with the live DOM.
Senior signal
Explain trade-offs with numbers from a profile, know why the structure fixes (state down, children) come before memoization, how the React Compiler changes that advice, and how state lives on fibers as a queue of updates.
What to check when reviewing keys and re-renders
Yazmadığın React komponentlərini — komanda yoldaşının, kitabxananın və ya AI assistentin kodunu — review edəndə bu siyahıdan istifadə et. Onsuz sıfırlanan və ya səhv sətrə düşən state, itən fokus və lazımsız re-render-lər gözdən qaçır.
- Siyahı key-ləri indeksdən və ya
Math.random()-dan yox, data-dan (item.id) götürülürmü? İndeks key-ləri element əlavə olunandan və ya siyahı sıralanandan sonra yazılmış mətni və fokusu səhv sətrə köçürür; təsadüfi key-lər isə hər render-də bütün sətirləri yenidən yaradır. Bir sətrə nəsə yaz, sonra siyahının başına element əlavə et: mətn öz elementinin yanında qalmalıdır. - Hansısa komponent başqa komponentin içində elan olunubmu? Hər render yeni funksiya, yəni React üçün yeni tip yaradır və komponent yenidən mount olunur: state itir, input isə hər hərfdən sonra fokusu itirir.
- State-i olan komponent JSX dəyişəndə öz tipini və mövqeyini saxlayırmı? Başqa sarğı element (
<section>əvəzinə<div>) və ya həmin slotda başqa element onu state-i ilə birlikdə unmount edir; sıfırlama lazımdırsa, state-i təmizləyən effekt yox,keyolmalıdır, məsələn,<Form key={user.id} />. - Tez-tez dəyişən state böyük alt ağacın üstündə dayanırmı? Hər yeniləmə state-in sahibindən aşağıdakı hər şeyi yenidən render edir: state aşağı enə bilərmi, baha hissə
childrenkimi ötürülə bilərmi? Nəyin və niyə render olunduğunu React DevTools Profiler göstərir. memo-nun və context-in müqayisə etdiyi dəyərlər sabitdirmi?memohər prop-uObject.isilə yoxlayır, ona görə inline obyekt, funksiya və ya JSXchildrenolanda komponent yenə render olunur; render zamanı qurulanvalue={{ … }}isə provider hər dəfə render olunanda bütün consumer-ləri yenidən render edir.
Use this list when you review React components you did not write: a teammate's, a library's or an AI assistant's. Without it, state that resets or lands on the wrong row, lost focus and needless re-renders slip through.
- Are list keys taken from the data (
item.id), not the index orMath.random()? Index keys move typed text and focus to the wrong row after an insert or a sort; random keys recreate every row on each render. Type into a row, then add an item at the top: the text must stay with its item. - Is a component declared inside another component? Each render makes a new function, a new type for React, so it remounts: state is lost and an input loses focus after every letter.
- Does a component with state keep its type and position when the JSX changes? A different wrapper (
<div>instead of<section>) or element in that slot unmounts it with its state; a wanted reset should use akey, as in<Form key={user.id} />, not an Effect that clears state. - Does state that changes often sit above a large subtree? Every update re-renders everything below its owner: can the state move down, or the expensive part come in as
children? The React DevTools Profiler shows what rendered and why. - Are the values that
memoand context compare stable?memochecks each prop withObject.is, so an inline object, function or JSXchildrenmakes it render anyway; a providervalue={{ … }}built during render re-renders every consumer each time the provider renders.
Check your understanding
Practise this
Hands-on work that uses this topic.
Build Your Own X
Incident Simulator
Weekly Challenges
See it in real code
Guided tours through the source of real libraries that rely on it.