State management and external stores
Where each piece of state belongs and why: local, shared, server, URL and form state, derived values, lifting state, context and its re-render cost, reducers, external stores with useSyncExternalStore, tearing, selectors and server-state caches.
This topic starts at Junior level.
Kinds of state and where each belongs
"State idarəetməsi" deyəndə çox vaxt kitabxana seçimi nəzərdə tutulur. Amma ilk sual başqadır: bu hansı növ state-dir? Hər növün öz tələbləri və təbii yeri var.
| Növ | Nümunələr | Təbii yeri |
|---|---|---|
| Lokal UI state-i | açıq dropdown, aktiv tab, yazılmaqda olan şərh | ondan istifadə edən komponentdə useState |
| Ortaq client state-i | səbət, tema, daxil olmuş istifadəçi | ən yaxın ortaq valideyn; çox sayda uzaq komponent oxuyursa, context və ya xarici store |
| Server state-i | API-dən gələn məhsullar, sifarişlər, istifadəçi profili | server state keşi (TanStack Query, SWR, framework-ün data yükləməsi) |
| URL state-i | filtrlər, sıralama, səhifə nömrəsi, paylaşmaq istədiyin tab | URL: route və search parametrləri |
| Form state-i | sahələrin dəyərləri, toxunulmuş sahələr, validasiya xətaları | formun özü, mürəkkəb formlar üçün isə form kitabxanası |
Bu fərq niyə vacibdir:
- Server state-i sənin deyil. O, serverdə yaşayır, başqaları onu dəyişə bilər və köhnəlir. Ona sadəcə dəyişən yox, keşləmə, yenidən sorğulama və invalidasiya lazımdır.
- URL state-i səhifə yenilənəndə də qalmalı, Back düyməsi ilə işləməli və link kimi paylaşıla bilməlidir.
useState-də saxlanan filtr refresh-dən sonra yox olur. - Form state-i qısaömürlüdür. Çox vaxt idarə olunmayan input-lar və submit zamanı
FormDatakifayət edir; formdan kənarda heç kimə hər düymə basışı lazım deyil. - Lokal UI state-i komponenti ilə birlikdə ölməlidir. Onu qlobal store-a qoysan, ekrandan uzun yaşayır, səhifələr arasında sızır və hər dəyişikliyi qlobal edir.
Bir səhifədə adətən bir neçə növ eyni vaxtda olur:
function ProductsPage() {
const [searchParams, setSearchParams] = useSearchParams();
const sort = searchParams.get("sort") ?? "popular";
const { data: products = [] } = useQuery({
queryKey: ["products", { sort }],
queryFn: () => fetchProducts({ sort }),
});
const [isFilterOpen, setFilterOpen] = useState(false);
const addToCart = useCartStore((state) => state.add);
// ...
}Sıralama URL-də yaşayır (burada React Router-in useSearchParams-ı ilə), məhsul siyahısı query keşində, panelin açıq olması lokal state-də, səbət isə ortaq store-da.
Lokaldan başla
Yaxşı default qayda: state-i ondan istifadə edən komponentdə saxla. Onu yalnız başqa komponentə lazım olanda yuxarı qaldır, React-dən kənara isə yalnız çox sayda uzaq komponentə lazım olanda və ya React-dən kənarda dəyişəndə çıxar. State-i sonradan köçürmək kiçik refaktorinqdir; hər şeyi saxlayan qlobal store-u açmaq isə böyük iş.
"State management" is often discussed as a choice of library. The first question is a different one: what kind of state is this? Each kind has different needs and a natural home.
| Kind | Examples | Natural home |
|---|---|---|
| Local UI state | an open dropdown, the active tab, a draft comment | useState in the component that uses it |
| Shared client state | the cart, the theme, the signed-in user | the closest common parent; context or an external store when many distant components read it |
| Server state | products, orders, the user's profile from the API | a server-state cache (TanStack Query, SWR, the framework's data loading) |
| URL state | filters, sort order, page number, a selected tab you want to share | the URL: route and search params |
| Form state | field values, touched fields, validation errors | the form itself, or a form library for complex forms |
Why the difference matters:
- Server state is not yours. It lives on a server, can be changed by other people and goes out of date. It needs caching, refetching and invalidation, not just a variable.
- URL state must survive a reload, work with the Back button and be shareable as a link. Kept in
useState, a filter disappears on refresh. - Form state is short-lived. Often uncontrolled inputs plus
FormDataon submit are enough; nothing outside the form needs every keystroke. - Local UI state should die with its component. Put it in a global store, and it outlives the screen, leaks between pages and makes every change global.
One page usually holds several kinds at once:
function ProductsPage() {
const [searchParams, setSearchParams] = useSearchParams();
const sort = searchParams.get("sort") ?? "popular";
const { data: products = [] } = useQuery({
queryKey: ["products", { sort }],
queryFn: () => fetchProducts({ sort }),
});
const [isFilterOpen, setFilterOpen] = useState(false);
const addToCart = useCartStore((state) => state.add);
// ...
}The sort order lives in the URL (here React Router's useSearchParams), the product list in a query cache, the panel's open state in local state, and the cart in a shared store.
Start local
A good default: keep state in the component that uses it. Move it up only when another component needs it, and out of React only when many distant components need it or when it changes outside React. Moving state later is a small refactor; untangling a global store that holds everything is a large one.
Derived state instead of duplicated state
react.dev-in "Choosing the State Structure" səhifəsi beş prinsip verir: əlaqəli state-i qruplaşdır, ziddiyyətlərdən qaç, artıq state saxlama, təkrarlamadan qaç, dərin iç-içəlikdən qaç. Real bug-ların çoxu ortadakı üç prinsipdən gəlir: bir-biri ilə uyğun olmalı iki state parçası bir gün uyğun olmur.
Saxlama, hesabla
function TodoList({ todos }) {
const [filter, setFilter] = useState("all");
const [visibleTodos, setVisibleTodos] = useState(todos);
useEffect(() => {
setVisibleTodos(todos.filter((todo) => filter === "all" || todo.done === (filter === "done")));
}, [todos, filter]);
// ...
}visibleTodos sinxron saxlanmalı olan surətdir. Hər dəyişiklik əvvəlcə köhnə siyahı ilə, effektdən sonra isə yenidən render olunur; effekti unudan istənilən kod yolu səhv data göstərir. Əvəzində onu render zamanı hesabla:
function TodoList({ todos }) {
const [filter, setFilter] = useState("all");
const visibleTodos = todos.filter((todo) => filter === "all" || todo.done === (filter === "done"));
// ...
}react.dev-in qaydası: nəyisə mövcud props və ya state-dən hesablamaq mümkündürsə, onu state-ə qoyma, render zamanı hesabla. Hesablama həqiqətən bahadırsa, onu useMemo-ya bük; dəyər yenə hesablanan dəyərdir, sadəcə keşlənir.
Surət yox, id saxla
items-in yanında selectedItem saxlamaq eyni obyekti iki yerdə təkrarlayır: elementi redaktə et, seçim köhnə başlığı göstərəcək. selectedId saxla və elementi render zamanı tap: items.find((item) => item.id === selectedId).
Ziddiyyəti mümkünsüz et
İki boolean — isSending və isSent — heç vaxt olmamalı bir vəziyyətə imkan verir: hər ikisi true. "typing", "sending" və "sent" dəyərləri olan bir status dəyişəni isə özü-özünə zidd ola bilməz.
Props-u state-də təkrarlama
function Message({ messageColor }) {
const [color, setColor] = useState(messageColor);
// ...
}useState arqumentindən yalnız ilk render-də istifadə edir, ona görə valideyn sonra "red" ötürəndə color "blue" olaraq qalır. Prop-dan birbaşa istifadə et. Həqiqətən yalnız ilk dəyər lazımdırsa, bunu adda bildir: initialColor və ya defaultColor.
react.dev's "Choosing the State Structure" gives five principles: group related state, avoid contradictions, avoid redundant state, avoid duplication, avoid deep nesting. Most real bugs come from the middle three: two pieces of state that are supposed to agree, and one day don't.
Compute it, don't store it
function TodoList({ todos }) {
const [filter, setFilter] = useState("all");
const [visibleTodos, setVisibleTodos] = useState(todos);
useEffect(() => {
setVisibleTodos(todos.filter((todo) => filter === "all" || todo.done === (filter === "done")));
}, [todos, filter]);
// ...
}visibleTodos is a copy that must be kept in sync. Every change renders once with the stale list and then again after the Effect, and any code path that forgets the Effect shows wrong data. Compute it during render instead:
function TodoList({ todos }) {
const [filter, setFilter] = useState("all");
const visibleTodos = todos.filter((todo) => filter === "all" || todo.done === (filter === "done"));
// ...
}react.dev's rule: when something can be calculated from the existing props or state, don't put it in state; calculate it during rendering. If the calculation is genuinely expensive, wrap it in useMemo; it is still derived, just cached.
Store ids, not copies
Keeping selectedItem next to items duplicates one object in two places: edit the item, and the selection shows the old title. Store selectedId and find the item during render: items.find((item) => item.id === selectedId).
Make contradictions impossible
isSending and isSent as two booleans allow a state that should never exist: both true. One status variable with the values "typing", "sending" and "sent" cannot contradict itself.
Don't mirror props
function Message({ messageColor }) {
const [color, setColor] = useState(messageColor);
// ...
}useState uses its argument only on the first render, so when the parent later passes "red", color stays "blue". Use the prop directly. If you really want only the first value, say so in the name: initialColor or defaultColor.
Lifting state up, context and its re-render cost
İki komponent birlikdə dəyişməlidirsə, react.dev-in cavabı state-i yuxarı qaldırmaqdır: onu hər ikisindən çıxar, ən yaxın ortaq valideyndə saxla və onu dəyişən event handler ilə birlikdə aşağı ötür. Hər unikal state parçasına bir komponent "sahiblik edir" — bu, vahid həqiqət mənbəyidir (single source of truth).
Yuxarı qaldırmaq props-un onlardan istifadə etməyən komponentlərdən keçməsinə səbəb ola bilər. Context-ə əl atmazdan əvvəl react.dev iki şey təklif edir: sadəcə props ötür (açıq data axını asan izlənir), və ya komponentləri ayır və JSX-i children kimi ötür ki, <Layout posts={posts} /> əvəzinə <Layout><Posts posts={posts} /></Layout> yazılsın.
Context-in qiyməti
Context dəyəri istənilən dərinliyə çatdırır. Qiyməti yeniləmələrin necə işləməsindədir: React value-su dəyişən provider-dən başlayaraq context-i oxuyan hər komponenti yenidən render edir, köhnə və yeni dəyərləri Object.is ilə müqayisə edir. İstehlakçıları memo-ya bükmək bunun qarşısını almır.
function ShopProvider({ children }) {
const [cart, setCart] = useState([]);
const [theme, setTheme] = useState("light");
const addToCart = (product) => setCart((lines) => addLine(lines, product));
return (
<ShopContext value={{ cart, addToCart, theme, setTheme }}>
{children}
</ShopContext>
);
}Burada iki problem gizlənib:
valueobyekti hər render-də yenidən yaranır, ona görəShopProviderhansı səbəbdən render olunursa olunsun, bütün istehlakçılar yenidən render olunur.- Əlaqəsiz data bir dəyəri bölüşür. Yalnız
addToCart-a ehtiyacı olan məhsul kartı da səbət dəyişəndə yenidən render olunur, çünkiaddToCart-ı saxlayan obyekt yenidir.
Düzəlişlər, təsirinə görə
- State-i aşağı endir. Bir komponentin istifadə etdiyi state (tək mətn sahəsindəki qaralama) ümumiyyətlə ortaq context-ə aid deyil.
- Context-ləri birlikdə dəyişən şeylərə görə böl, action-ları isə ayrıca context-ə çıxar.
setStatefunksiyaları heç vaxt dəyişmir, ona görə bir dəfə qurulmuş action-lar dəyəri sabit qalır. - Dəyərləri sabitləşdir: obyektlər üçün
useMemo, funksiyalar üçünuseCallback. Bu, provider-in yenidən render olunmasından gələn re-render-ləri dayandırır, real dəyişiklikdən gələnləri yox: hər şeyi bir yerə yığan dəyəri memo etsən də, onun istənilən hissəsi dəyişəndə o da dəyişir. - Selector-lu xarici store-dan istifadə et — çox sayda komponentin hər biri tez dəyişən state-in kiçik bir hissəsinə ehtiyac duyanda.
Context çox yerdə oxunan və nadir dəyişən dəyərlər üçün yaxşıdır: tema, cari hesab, locale, router.
Həftəlik çağırışlardakı Context fırtınası çağırışında context re-render-lərini tapıb aradan qaldırmağı məşq edə bilərsən: bir mağaza context-i istifadəçini, temanı, səbəti və hədiyyə qeydini saxlayır, bir bitki əlavə etmək isə bütün 24 məhsul kartını yenidən render edir.
When two components must change together, react.dev's answer is to lift state up: remove it from both, keep it in their closest common parent and pass it down with an event handler that changes it. For each unique piece of state one component "owns" it; this is the single source of truth.
Lifting can make props travel through components that don't use them. Before reaching for context, react.dev suggests two things: just pass props (explicit data flow is easy to follow), or extract components and pass JSX as children, so that <Layout><Posts posts={posts} /></Layout> replaces <Layout posts={posts} />.
What context costs
Context delivers a value to any depth. The price is how updates work: React re-renders every component that reads the context, starting from the provider whose value changed, comparing old and new values with Object.is. Wrapping consumers in memo does not prevent this.
function ShopProvider({ children }) {
const [cart, setCart] = useState([]);
const [theme, setTheme] = useState("light");
const addToCart = (product) => setCart((lines) => addLine(lines, product));
return (
<ShopContext value={{ cart, addToCart, theme, setTheme }}>
{children}
</ShopContext>
);
}Two problems are hidden here:
- The
valueobject is created on every render, so every consumer re-renders wheneverShopProviderrenders for any reason. - Unrelated data shares one value. A product card that only needs
addToCartstill re-renders when the cart changes, because the object holdingaddToCartis new.
Fixes, in order of impact
- Move state down. State that one component uses (a draft in a single text field) does not belong in a shared context at all.
- Split contexts by what changes together, and give actions a context of their own.
setStatefunctions never change, so an actions value built once stays stable. - Stabilize values with
useMemofor objects anduseCallbackfor functions. This stops re-renders caused by the provider re-rendering, but not those caused by a real change: memoizing a value that bundles everything still changes it whenever any part of it changes. - Use an external store with selectors when many components each need a small slice of frequently changing state.
Context is a good fit for values that are read in many places and change rarely: the theme, the current account, the locale, the router.
The Context storm challenge in Weekly Challenges lets you practise finding and removing context re-renders: one shop context holds the user, the theme, the cart and a gift note, and adding a single plant re-renders all 24 product cards.
Reducers and immutable updates
Bir neçə event handler eyni state-i bir-biri ilə əlaqəli şəkildə yeniləyəndə useReducer bu məntiqi bir təmiz funksiyaya köçürür: (state, action) => nextState. Komponentlər yalnız nə baş verdiyini təsvir edir (dispatch({ type: "added", product })), state-in necə dəyişəcəyinə isə reducer qərar verir.
function cartReducer(state, action) {
switch (action.type) {
case "added": {
const exists = state.lines.some((line) => line.id === action.product.id);
const lines = exists
? state.lines.map((line) =>
line.id === action.product.id ? { ...line, qty: line.qty + 1 } : line,
)
: [...state.lines, { id: action.product.id, qty: 1 }];
return { ...state, lines };
}
case "cleared":
return { ...state, lines: [] };
default:
return state;
}
}Immutability niyə zövq məsələsi deyil
React nəyinsə dəyişib-dəyişmədiyinə referansa görə qərar verir. setState və ya dispatch cari state ilə Object.is-ə görə eyni olan dəyər alanda React həmin komponentin re-render-ini ötürür. memo, dependency array-lər və store selector-ları da referansları müqayisə edir. Dəyişdirən (mutating) reducer bunların hamısını sındırır:
case "added":
state.lines.push({ id: action.product.id, qty: 1 });
return state;Reducer eyni obyekti qaytarır, ona görə React dəyişiklik görmür və ekran yenilənmir, halbuki data dəyişib. Növbəti əlaqəsiz render onu birdən göstərir və bug təsadüfi görünür. Strict Mode-da React development zamanı təmiz olmayan kodu üzə çıxarmaq üçün reducer-ləri iki dəfə çağırır; burada bu, sətri iki dəfə əlavə edir.
Immutable yeniləmə yalnız dəyişən yolu kopyalayır, qalan hər şeyi təkrar istifadə edir. Yuxarıdakı reducer-də dəyişməyən sətirlər referanslarını saxlayır, ona görə memo(CartLine) komponenti onları ötürür, state.user-i oxuyan selector isə səbət dəyişəndə dəyişiklik görmür. İncə dənəli re-render-ləri mümkün edən məhz bu structural sharing-dir. Immer kimi kitabxanalar (Redux Toolkit-in createSlice-ı ondan istifadə edir) "dəyişdirən" görünüşlü kod yazmağa imkan verir və eyni immutable nəticəni yaradır.
Reducer və context birlikdə
Çox sayda uzaq komponentin oxuduğu və dəyişdiyi ekran üçün react.dev ikisini birləşdirir: bir context state üçün, biri də dispatch üçün. dispatch komponentin bütün ömrü boyu sabitdir, ona görə yalnız action göndərən komponentlər ("Add" düyməsi) siyahı dəyişdiyinə görə heç vaxt yenidən render olunmur. Bir tətbiqdə hər feature üçün belə bir cüt ola bilər.
When several event handlers update the same state in related ways, useReducer moves that logic into one pure function: (state, action) => nextState. Components only describe what happened (dispatch({ type: "added", product })), and the reducer decides how the state changes.
function cartReducer(state, action) {
switch (action.type) {
case "added": {
const exists = state.lines.some((line) => line.id === action.product.id);
const lines = exists
? state.lines.map((line) =>
line.id === action.product.id ? { ...line, qty: line.qty + 1 } : line,
)
: [...state.lines, { id: action.product.id, qty: 1 }];
return { ...state, lines };
}
case "cleared":
return { ...state, lines: [] };
default:
return state;
}
}Why immutability is not a style preference
React decides whether something changed by reference. When setState or dispatch receives a value that is Object.is-equal to the current state, React skips re-rendering that component. memo, dependency arrays and store selectors all compare references too. A mutating reducer breaks every one of them:
case "added":
state.lines.push({ id: action.product.id, qty: 1 });
return state;The reducer returns the same object, so React sees no change and the screen does not update, although the data did change. The next unrelated render suddenly shows it, which makes the bug look random. In Strict Mode, React calls reducers twice in development to surface impure code; here that pushes the line twice.
Immutable updates copy only the path that changed and reuse everything else. In the reducer above, unchanged lines keep their references, so a memo(CartLine) component skips them, and a selector that reads state.user does not see a change when the cart changes. This structural sharing is what makes fine-grained re-renders possible. Libraries such as Immer (used by Redux Toolkit's createSlice) let you write mutating-looking code that produces the same immutable result.
Reducer plus context
For a screen whose state many distant components read and change, react.dev combines the two: one context for the state and one for dispatch. dispatch is stable for the component's lifetime, so components that only send actions (an "Add" button) never re-render because the list changed. You can have many such pairs in one app, one per feature.
External stores: subscribe, snapshots and selectors
Bəzi state React-dən kənarda yaşayır: Redux və ya Zustand store-u, modul səviyyəsində keş, navigator.onLine kimi brauzer API-si. React onun dəyişdiyini görə bilmir, ona görə store-dan iki şey lazımdır: cari dəyəri oxumaq yolu (snapshot) və dəyişiklikdən xəbər tutmaq yolu (subscribe). React-in bunun üçün hook-u useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?)-dur.
Bu müqaviləyə uyğun store kiçikdir. Zustand-ın nüvəsi (vanilla.ts-dəki createStore) belə qurulub:
function createStore(createState) {
let state;
const listeners = new Set();
const getState = () => state;
const setState = (partial) => {
const next = typeof partial === "function" ? partial(state) : partial;
if (Object.is(next, state)) return;
const previous = state;
state = Object.assign({}, state, next);
listeners.forEach((listener) => listener(state, previous));
};
const subscribe = (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
state = createState(setState, getState);
return { getState, setState, subscribe };
}State içində gizlidir, listener-lər Set-də saxlanır, setState isə dəyişikliyi səthi şəkildə yeni obyektə birləşdirir, ona görə referansları müqayisə edən hər kəs dəyişikliyi görür. Real versiya bir də replace flag-ı qəbul edir.
Selector-lar və bərabərlik
function useStore(store, selector) {
return useSyncExternalStore(store.subscribe, () => selector(store.getState()));
}
const count = useStore(cartStore, (state) => state.lines.length);Store-un hər dəyişikliyindən sonra React snapshot funksiyasını yenidən çağırır və nəticə Object.is-ə görə fərqlənəndə komponenti yenidən render edir. Selector komponentin "mənə yalnız bu hissə lazımdır" deməsinin yoludur. Bərabərlik isə nəyin dəyişiklik sayıldığını müəyyən edən qaydadır:
- Primitiv (
lines.length) və ya mövcud referans (state.user) seçməkObject.isilə yaxşı işləyir. - Yeni qurulan obyekt və ya massiv (
{ count, total },lines.map(...)) hər çağırışda yeni referans verir. React-Redux-unuseSelector-ı (default olaraq===) onda hər action-da yenidən render edir;useSyncExternalStoreilə isə sonsuz dövrə girə bilər. Səthi müqayisədən istifadə et (React-Redux-dashallowEqual, Zustand-dauseShallow) və ya dəyərləri bir-bir seç.
Redux hər dispatch-dən sonra, reducer eyni state qaytarsa belə, bütün listener-ləri çağırır; komponentləri artıq re-render-dən qoruyan useSelector-dakı selector müqayisəsidir.
Platformada
Özün qur bölməsindəki Mini state kitabxanası layihəsində bunu sıfırdan yazırsan: Redux üslubunda store, abunələr, bərabərlik funksiyalı selector-lar, middleware və useSyncExternalStore üzərində hook. Zustand: bütün store 164 sətirdə turu isə v5.1.0 versiyasındakı real vanilla.ts və react.ts fayllarını oxuyur.
Some state lives outside React: a Redux or Zustand store, a module-level cache, a browser API such as navigator.onLine. React cannot see it change, so it needs two things from the store: a way to read the current value (a snapshot) and a way to be told that it changed (subscribe). React's hook for this is useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?).
A store that fits this contract is small. This is the shape of Zustand's core (createStore in vanilla.ts):
function createStore(createState) {
let state;
const listeners = new Set();
const getState = () => state;
const setState = (partial) => {
const next = typeof partial === "function" ? partial(state) : partial;
if (Object.is(next, state)) return;
const previous = state;
state = Object.assign({}, state, next);
listeners.forEach((listener) => listener(state, previous));
};
const subscribe = (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
state = createState(setState, getState);
return { getState, setState, subscribe };
}The state is private to a , listeners sit in a Set, and setState merges shallowly into a new object, so anything that compares references sees the change. The real one also takes a replace flag.
Selectors and equality
function useStore(store, selector) {
return useSyncExternalStore(store.subscribe, () => selector(store.getState()));
}
const count = useStore(cartStore, (state) => state.lines.length);After every store change React calls the snapshot function again and re-renders the component only if the result differs by Object.is. A selector is how a component says "I only care about this slice". Equality is the rule that decides what counts as a change:
- Selecting a primitive (
lines.length) or an existing reference (state.user) works withObject.is. - Selecting a newly built object or array (
{ count, total },lines.map(...)) gives a new reference on every call. React-Redux'suseSelector(===by default) then re-renders on every action; withuseSyncExternalStoreit can loop forever. Use a shallow comparison (shallowEqualin React-Redux,useShallowin Zustand) or select values one by one.
Redux calls every listener after every dispatch, even if the reducer returned the same state; it is the selector comparison in useSelector that keeps components from re-rendering.
On the platform
In the Mini State Library project (Build Your Own X) you write this from scratch: a Redux-style store, subscriptions, selectors with an equality function, middleware and a hook on useSyncExternalStore. The tour Zustand: the whole store in 164 lines reads the real vanilla.ts and react.ts at v5.1.0.
Tearing, concurrent rendering and stable snapshots
React 18-dən bəri render concurrent ola bilər: transition zamanı React input-u emal etmək üçün render-i dayandırıb sonra davam etdirə bilər. React öz state-ini (useState, context) belə fasilələr boyunca ardıcıl saxlayır, amma sahibi olmadığı dəyərləri qoruya bilmir. Komponent render zamanı dəyişkən store-u birbaşa oxuyursa və React fasilədə ikən store dəyişirsə, dəyişiklikdən əvvəl render olunan komponentlər köhnə, sonra render olunanlar isə yeni dəyəri göstərir. React 18 işçi qrupu buna tearing deyir: UI eyni state üçün bir neçə dəyər göstərir.
useSyncExternalStore bunun qarşısını almaq üçündür. React store-u yalnız getSnapshot vasitəsilə oxuyur və commit-dən əvvəl onu yoxlayır: react.dev-ə görə, transition yeniləməsində React DOM-a dəyişiklikləri tətbiq etməzdən dərhal əvvəl getSnapshot-ı ikinci dəfə çağırır, dəyər dəyişibsə, yeniləməni bloklayan yeniləmə kimi yenidən başladır ki, ekrandakı hər komponent store-un eyni versiyasını göstərsin. Qiyməti budur: store dəyişikliyindən gələn yeniləmələr sinxrondur; transition-dakı useState yeniləmələri kimi hissələrə bölünə bilmir.
Snapshot müqaviləsi
Store dəyişməyibsə, getSnapshot-ın təkrar çağırışları eyni dəyəri qaytarmalıdır (Object.is-ə görə). React onu hər render-də və store-un hər bildirişindən sonra çağırır; fərqli dəyər "yenidən render et" deməkdir.
const summary = useSyncExternalStore(store.subscribe, () => ({
count: store.getState().todos.length,
}));Bu snapshot hər çağırışda yeni obyektdir, ona görə React heç vaxt sabit dəyər görmür. React 19 əvvəlcə "The result of getSnapshot should be cached to avoid an infinite loop" yazır, sonra "Maximum update depth exceeded" ilə dayanır. Düzəlişlər:
const count = useSyncExternalStore(store.subscribe, () => store.getState().todos.length);
const { count, add } = useTodoStore(
useShallow((state) => ({ count: state.todos.length, add: state.add })),
);Birincisi primitiv qaytarır. İkincisi Zustand-dır: onun sənədləri xəbərdarlıq edir ki, v5-də hər render-də yeni referans qaytaran selector sonsuz yeniləmə dövrünə səbəb ola bilər, useShallow isə sahələri səthi bərabər qaldıqca əvvəlki obyekti qaytarır. React-Redux üçüncü yolla gedir: seçimi memo edən useSyncExternalStoreWithSelector-dan istifadə edir.
Daha iki qayda
subscribesabit olmalıdır. Hər render-də yeni funksiya React-i hər dəfə abunəni ləğv edib yenidən abunə olmağa məcbur edir; onu komponentdən kənarda elan et və ya memo et.- Snapshot-lar immutable-dır. Mənbə dəyişkəndirsə, keşlənmiş snapshot qaytar və onu yalnız data dəyişəndə əvəz et.
Server render üçün üçüncü arqument — getServerSnapshot — serverdə və hydration zamanı eyni dəyəri qaytarmalıdır; onsuz komponenti serverdə render etmək xəta atır. Zustand ora store-un ilkin state-ini ötürür, server render-in ilkin state-i göstərməsinin səbəbi budur.
Since React 18, rendering can be concurrent: during a transition React may pause a render to handle input and continue later. React keeps its own state (useState, context) consistent across such pauses, but it cannot protect values it does not own. If a component reads a mutable store directly during render and the store changes while React is paused, components rendered before the change show the old value and those rendered after it show the new one. The React 18 working group calls this tearing: the UI shows multiple values for the same state.
useSyncExternalStore exists to prevent it. React reads the store only through getSnapshot and checks it before committing: react.dev says that for a transition update React calls getSnapshot a second time just before applying changes to the DOM, and if the value changed, it restarts the update as a blocking one, so every component on screen reflects the same version of the store. The trade-off is that updates caused by a store change are synchronous; they cannot be time-sliced the way useState updates in a transition can.
The snapshot contract
While the store has not changed, repeated calls to getSnapshot must return the same value (by Object.is). React calls it during every render and after every store notification; a different value means "re-render".
const summary = useSyncExternalStore(store.subscribe, () => ({
count: store.getState().todos.length,
}));This snapshot is a new object on every call, so React never sees a stable value. React 19 logs "The result of getSnapshot should be cached to avoid an infinite loop" and then stops with "Maximum update depth exceeded". The fixes:
const count = useSyncExternalStore(store.subscribe, () => store.getState().todos.length);
const { count, add } = useTodoStore(
useShallow((state) => ({ count: state.todos.length, add: state.add })),
);The first returns a primitive. The second is Zustand: its docs warn that a selector returning a new reference on every render can trigger infinite update loops in v5, and useShallow returns the previous object while its fields are shallowly equal. React-Redux takes a third route: it uses useSyncExternalStoreWithSelector, which memoizes the selection.
Two more rules
subscribemust be stable. A new function on each render makes React unsubscribe and subscribe again every time; declare it outside the component or memoize it.- Snapshots are immutable. If the source is mutable, return a cached snapshot and replace it only when the data changes.
For server rendering, the third argument getServerSnapshot must return the same value on the server and during hydration; without it, rendering the component on the server throws. Zustand passes the store's initial state there, which is why a server render shows the initial state.
Server state is a cache, not state
TanStack Query sənədləri server state-ini fərqli edən şeyləri sadalayır: o, nəzarət etmədiyin yerdə uzaqda saxlanır, asinxron API-lər tələb edir, onu dəyişə bilən başqa insanlarla bölüşülür və köhnələ bilər. Onu client store-da { data, loading, error } kimi saxlamaq keşi əl ilə yazmaq deməkdir: nə vaxt yenidən sorğulamaq, təkrar sorğulardan necə qaçmaq, köhnə data-nı necə atmaq, ardıcıllığı pozulmuş cavablarla nə etmək. Tətbiqlərin çoxu bunların bir hissəsini səhv edir.
Server state kitabxanası keşi öz üzərinə götürür:
function useProducts(sort) {
return useQuery({
queryKey: ["products", { sort }],
queryFn: () => fetchProducts({ sort }),
staleTime: 60_000,
});
}
function useAddReview() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: postReview,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["products"] }),
});
}TanStack Query necə davranır (v5)
- Hər key üçün bir keş girişi.
queryKeysabit sətrə hash olunur. Eyni key-li iki komponent bir query-ni bölüşür, ona görə hər ikisi birlikdə mount olanda bir sorğu gedir (deduplikasiya). Query funksiyasının istifadə etdiyi hər dəyər key-də olmalıdır; biri çatışmırsa, fərqli sorğular bir girişi bölüşür — məsələn, bir filtrin nəticələri digəri üçün göstərilir. staleTime-ın default-u0-dır: keşlənmiş data dərhal köhnəlmiş sayılır. Köhnəlmiş data yenə dərhal göstərilir; query-ni istifadə edən yeni komponent mount olanda, pəncərə yenidən fokuslananda və şəbəkə bərpa olunanda arxa planda yenidən sorğulanır. Köhnəlmə məhz bu anlarda yoxlanılır; sadəcə vaxt bitdiyinə görə heç nə sorğulanmır.gcTime-ın default-u 5 dəqiqədir: mount olunmuş istifadəçisi qalmayan (qeyri-aktiv) query bundan sonra silinir.- Uğursuz sorğular xəta göstərilməzdən əvvəl eksponensial gecikmə ilə 3 dəfə təkrarlanır.
- Structural sharing: eyni JSON qaytaran yenidən sorğu köhnə referansları saxlayır, ona görə komponentlər və memo edilmiş selector-lar dəyişiklik görmür.
invalidateQueriesuyğun gələn query-ləri köhnəlmiş kimi işarələyir (key prefiksi onunla başlayan bütün key-lərə uyğun gəlir) və hazırda render olunanları yenidən sorğulayır.
isPending hələ data olmadığını bildirir; isFetching isə istənilən sorğu zamanı, arxa plandakı yenidən sorğu da daxil olmaqla, true olur. isFetching üçün spinner göstərmək hər pəncərə fokusunda loader-in yanıb-sönməsinə səbəb olur.
TanStack Query: useQuery-nin həyatı turu bir çağırışı QueryClient, QueryCache, Query və QueryObserver boyunca izləyir: hər key üçün bir ortaq query, hər komponent üçün bir observer.
Client store-a nə qalır
TanStack sənədləri açıq deyir ki, kitabxana client state idarəetməsini əvəz etmir. Server data-sı query keşinə köçəndən sonra qalan qlobal client state-i adətən kiçik olur: tema, qaralama, UI flag-ları, bəzən səbət. Əsl qazanc da budur: client store yalnız client-in həqiqətən sahib olduğu şeylərə qədər kiçilir.
The TanStack Query docs describe what makes server state different: it is persisted remotely in a place you don't control, needs asynchronous APIs, is shared with other people who can change it, and can go out of date. Putting it in a client store as { data, loading, error } means writing a cache by hand: when to refetch, how to avoid duplicate requests, how to drop old data, how to handle out-of-order responses. Most apps get some of that wrong.
A server-state library owns the cache:
function useProducts(sort) {
return useQuery({
queryKey: ["products", { sort }],
queryFn: () => fetchProducts({ sort }),
staleTime: 60_000,
});
}
function useAddReview() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: postReview,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["products"] }),
});
}How TanStack Query behaves (v5)
- One cache entry per key. The
queryKeyis hashed into a stable string. Two components with the same key share one query, so mounting both at once sends one request (deduplication). Every value the query function uses belongs in the key; a missing one makes different requests share one entry, such as the results for one filter shown for another. staleTimedefaults to0: cached data is considered stale at once. Stale data is still shown immediately; it is refetched in the background when a new component using the query mounts, when the window is refocused and when the network reconnects. Staleness is checked at those moments; nothing is fetched just because the time ran out.gcTimedefaults to 5 minutes: a query with no mounted users (inactive) is removed after that.- Failures are retried 3 times with exponential backoff before the query shows an error.
- Structural sharing: a refetch that returns equal JSON keeps the old references, so components and memoized selectors see no change.
invalidateQueriesmarks matching queries stale (a key prefix matches every key that starts with it) and refetches the ones that are being rendered.
isPending means there is no data yet; isFetching is true during any fetch, including a background refetch. Showing a spinner for isFetching makes every window focus flash a loader.
The TanStack Query tour TanStack Query: the life of useQuery follows one call through QueryClient, QueryCache, Query and QueryObserver: one shared query per key, one observer per component.
What is left for the client store
TanStack's docs are explicit that the library is not a replacement for client state management. Once server data moves into a query cache, the remaining global client state is usually small: the theme, a draft, UI flags, sometimes a cart. That is the real payoff: the client store shrinks to what the client actually owns.
Choosing the right home, and common mistakes
Redux Toolkit, Zustand və ya sadə context arasında seçim hər state parçası üçün düzgün yeri seçməkdən az əhəmiyyətlidir. "State idarəetməsi problemlərinin" çoxu səhv yerdə saxlanan state-dir. Bu sualları ardıcıllıqla ver:
- Onu hesablamaq olarmı — props-dan, başqa state-dən və ya URL-dən? Onda saxlama.
- Serverdən gəlir? Server state keşi və ya framework-ün data yükləməsi; client store-da surəti heç vaxt.
- Səhifə yenilənəndə qalmalı və ya paylaşıla bilməlidir? URL.
- Doldurulmaqda olan formdur? Formun özü və ya form kitabxanası.
- Ondan bir komponent istifadə edir? Orada
useState. - Bir neçə yaxın komponent istifadə edir? Ortaq valideynə qaldır.
- Çox sayda uzaq komponent oxuyur və nadir dəyişir? Context.
- Çox sayda komponentin hər birinə onun bir hissəsi lazımdır və tez dəyişir? Selector-lu xarici store.
Real kodda rast gəlinən səhvlər
- API data-sının Redux-a və ya Zustand-a kopyalanması. Data köhnəlir, eyni siyahını üç komponent ayrı-ayrı sorğulayır, hər mutasiya isə bir neçə yerdə əl ilə yeniləmə tələb edir.
- Filtrlər və səhifələmə
useState-də. Refresh onları itirir, Back düyməsi onlara məhəl qoymur, linki isə heç kim paylaşa bilmir. - Hər düymə basışı qlobal store-da. Hər dəyişiklik bütün abunəçilərin selector-larını işə salır və lokal davranışı qlobal edir. Input state-ini lokal saxla və onu submit zamanı və ya debounce ilə ötür.
- Bir nəhəng context. Hər dəyişiklikdə hər istehlakçı yenidən render olunur.
- Səthi müqayisəsiz yeni obyekt quran selector-lar: hər dəyişiklikdə re-render və ya sonsuz dövr.
- Bir state-i digərinə sinxronlaşdıran effektlər. İkinci dəyəri hesablamaq olursa, hesabla; hadisəyə reaksiyadırsa, onu event handler-də et.
- State-i dəyişdirib (mutate edib) UI-ın niyə yenilənmədiyinə təəccüblənmək.
Praktik default
Tipik React tətbiqi üçün: lokal olaraq useState və useReducer, paylaşılan hər şey üçün URL, API data-sı üçün server state kitabxanası (və ya Server Components və loader-lər), qalanı üçün isə bir kiçik client store və ya bir-iki fokuslu context. Kitabxananı real ehtiyac yarananda əlavə et: çox sayda komponent tez dəyişən state-in hissələrini oxuyanda, logging və ya persistence kimi middleware lazım olanda, ya da devtools istəyəndə.
Choosing between Redux Toolkit, Zustand or plain context matters less than choosing the right home for each piece of state. Most "state management problems" are state in the wrong place. Ask, in order:
- Can it be computed from props, other state or the URL? Then don't store it.
- Does it come from the server? A server-state cache or the framework's data loading, never a copy in a client store.
- Should it survive a reload or be shareable? The URL.
- Is it a form being filled in? The form, or a form library.
- Does one component use it?
useStatethere. - Do a few nearby components use it? Lift it to their common parent.
- Do many distant components read it, and does it change rarely? Context.
- Do many components each need a slice of it, and does it change often? An external store with selectors.
Mistakes seen in real code
- API data copied into Redux or Zustand. It goes stale, the same list is fetched by three components, and every mutation needs manual updates in several places.
- Filters and pagination in
useState. Refresh loses them, the Back button ignores them, and nobody can share the link. - Every keystroke in a global store. Each change runs every subscriber's selector and makes local behaviour global. Keep input state local and commit it on submit or with a debounce.
- One giant context. Every consumer re-renders on every change.
- Selectors that build new objects without a shallow comparison: re-renders on every change, or an infinite loop.
- Effects that sync one state into another. If the second value can be computed, compute it; if it is a reaction to an event, do it in the event handler.
- Mutating state and wondering why the UI does not update.
A practical default
For a typical React app: useState and useReducer locally, the URL for anything shareable, a server-state library (or Server Components and loaders) for API data, and one small client store or a couple of focused contexts for what remains. Add a library when a real need appears: many components reading slices of frequently changing state, middleware such as logging or persistence, or devtools.
Interview tips
30 saniyəlik cavab. "Əvvəlcə state-in növünü müəyyən edirəm: lokal UI, ortaq client, server, URL və ya form state-i. Hər birinin təbii yeri var: useState, ortaq valideyn və ya context, server state keşi, URL, form. Hesablana bilən şeyi saxlamıram. Çox komponentin oxuduğu ortaq state üçün useSyncExternalStore üzərində selector-lu xarici store istifadə edirəm ki, komponentlər yalnız öz hissələri dəyişəndə render olunsun."
Gözlənilən suallar
- Context, yoxsa Redux/Zustand? Context dəyəri aşağı ötürür; o dəyişəndə hər istehlakçı yenidən render olunur. Selector-lu store isə hər komponentə bir hissəyə abunə olmağa imkan verir. Context nadir dəyişən dəyərlər üçündür (tema, hesab, locale).
- Komponentlərim niyə yenidən render olunur? Səbəbləri bir-bir say: valideyn render olunub, context-in yeni dəyəri (çox vaxt inline obyekt), yeni obyekt qaytaran selector, iki dəfə saxlanıb effektdə sinxronlaşdırılan state.
- Niyə immutable yeniləmələr? React,
memo, dependency array-lər və selector-lar referanslarıObject.isilə müqayisə edir. Mutasiya eyni referansı verir, ona görə heç nə yenilənmir; dəyişən yolu kopyalamaq isə dəyişməyən hissələri eyni saxlayır. - Tearing nədir və
useSyncExternalStoreniyə var? Concurrent render fasilə verə bilər; o vaxt dəyişən store bir ekranda iki dəyər göstərir.useSyncExternalStorecommit-dən əvvəl snapshot-ı yoxlayır və bloklayan render-ə keçir. - API data-sını niyə Redux-da saxlamayaq? Server state-inə keşləmə, deduplikasiya, arxa planda yenidən sorğulama və invalidasiya lazımdır.
staleTime(default 0),gcTime(5 dəqiqə) vəinvalidateQueries-i adlandır. - Kiçik store yaz.
statesaxlayan closure, listener-lərdən ibarətSet,getState,Object.isyoxlaması olansetState, abunəni ləğv edən funksiya qaytaransubscribevəuseSyncExternalStoreüzərində hook.
Bal itirdən səhvlər
memo-nun context re-render-lərini dayandırdığını demək. Dayandırmır.getSnapshot-dan və ya selector-dan səthi bərabərlik olmadan yeni obyekt qaytarmaq.- "Qlobal state"-i server, URL və client state-inə ayırmaq əvəzinə bir səbət kimi görmək.
- State-i təsvir etməzdən əvvəl kitabxana seçmək.
Senior səviyyəni göstərən məqamlar
Kompromislərlə danış: sinxron store yeniləmələri və transition-lar, provider dəyərinin qiyməti və selector abunələri, hər girişi əhatə edən keş key-ləri, arxitekturanı dəyişməzdən əvvəl re-render problemini React DevTools Profiler ilə necə ölçərdin.
A 30-second answer. "First I decide what kind of state it is: local UI, shared client, server, URL or form state. Each has a natural home: useState, a common parent or context, a server-state cache, the URL, the form. I don't store what I can derive. For shared state read by many components I use an external store with selectors on useSyncExternalStore, so components re-render only when their slice changes."
Questions you are likely to get
- Context or Redux/Zustand? Context passes a value down; every consumer re-renders when it changes. A store with selectors lets each component subscribe to a slice. Context suits rarely changing values (theme, account, locale).
- Why do my components re-render? Walk through the causes: the parent rendered, a new context value (often an inline object), a selector that returns a new object, state stored twice and synced in an Effect.
- Why immutable updates? React,
memo, dependency arrays and selectors compare references withObject.is. Mutation gives the same reference, so nothing updates; copying the changed path keeps unchanged parts identical. - What is tearing, and why does
useSyncExternalStoreexist? Concurrent rendering can pause; a store that changes meanwhile shows two values on one screen.useSyncExternalStorechecks the snapshot before committing and falls back to a blocking render. - Why not keep API data in Redux? Server state needs caching, deduplication, background refetching and invalidation. Name
staleTime(0 by default),gcTime(5 minutes) andinvalidateQueries. - Implement a tiny store. A closure with
state, aSetof listeners,getState,setStatewith anObject.ischeck,subscribereturning an unsubscribe function, and a hook onuseSyncExternalStore.
Mistakes that cost points
- Saying
memostops context re-renders. It does not. - Returning a new object from
getSnapshotor a selector without shallow equality. - Treating "global state" as one bucket instead of separating server, URL and client state.
- Picking a library before describing the state.
Senior signal
Talk in trade-offs: synchronous store updates versus transitions, the cost of a provider value versus selector subscriptions, cache keys that include every input, and how you would measure a re-render problem with the React DevTools Profiler before changing the architecture.
What to check when reviewing state and stores
Yazmadığın state kodunu — komanda yoldaşının, kitabxananın və ya AI assistentin kodunu — review edəndə bu siyahıdan istifadə et. State bug-larının çoxu səhv yerdə və ya səhv formada saxlanan state-dir: uyğunluğunu itirən iki surət, refresh-dən sonra itən filtr, yenilənməyən ekran.
- Hansısa state hesablana bilən şeyin surətidirmi? Effektlə sinxron saxlanan
useStateəvvəlcə köhnə data ilə render olunur, hansısa kod yolu onu unudan kimi isə uyğunluğunu itirir; dəyəri render zamanı hesabla. Elementin surətini yox,selectedIdsaxla, prop-u dauseState-ə kopyalama: onun arqumenti yalnız ilk render-də oxunur. - State mutasiya olunmadan dəyişdirilirmi? React,
memovə selector-lar referanslarıObject.isilə müqayisə edir, ona görə state-ipush,sort()və yastate.field = …ilə dəyişdirmək ekranı yeniləmir. Dəyişən hər səviyyə yeni obyekt və ya massiv olmalıdır, məsələn,{ ...state, lines }. - API data-sı client store-da surət kimi yox, server state keşində saxlanırmı? Surət köhnəlir, bir neçə komponent onu ayrı-ayrı sorğulayır, hər mutasiyadan sonra isə əl ilə yenilənməlidir. Query keşində query funksiyasının istifadə etdiyi hər dəyər key-də olmalıdır, yoxsa fərqli sorğular bir girişi bölüşür.
- Filtrlər, sıralama və səhifə nömrəsi URL-də saxlanırmı?
useState-də olanda refresh onları itirir, Back düyməsi onlara məhəl qoymur, linki isə paylaşmaq olmur. Filtr seç, səhifəni yenilə və Back düyməsini bas. - Selector-lar və
getSnapshotprimitiv və ya mövcud referans qaytarırmı? Yeni qurulan obyekt və ya massiv ({ count, total },.map(…)) hər çağırışda yenidir: komponent store-un hər dəyişikliyində yenidən render olunur,useSyncExternalStoreilə isə sonsuz dövrə girə bilər. Dəyərləri bir-bir seç və ya səthi müqayisə et.
Use this list when you review state code you did not write: a teammate's, a library's or an AI assistant's. Most state bugs are state in the wrong place or shape: two copies that disagree, a filter lost on reload, a screen that does not update.
- Is any state a copy of something that can be computed? A
useStatesynced by an Effect renders stale data first and drifts once a code path forgets it; compute the value during render. StoreselectedId, not a copy of the item, and don't copy a prop intouseState: its argument is read only on the first render. - Is state changed without mutation? React,
memoand selectors compare references withObject.is, so mutating state withpush,sort()orstate.field = …leaves the screen unchanged. Each changed level needs a new object or array, such as{ ...state, lines }. - Does API data live in a server-state cache rather than a copy in a client store? A copy goes stale, gets fetched by several components and needs manual updates after every mutation. In a query cache, every value the query function uses belongs in the key, or different requests share one entry.
- Do filters, sort order and page number live in the URL? In
useStatethey vanish on reload, the Back button ignores them and the link cannot be shared. Set a filter, reload and press Back. - Do selectors and
getSnapshotreturn a primitive or an existing reference? A newly built object or array ({ count, total },.map(…)) is new on every call: the component re-renders on every store change, and withuseSyncExternalStoreit can loop forever. Select values one by one or compare shallowly.
Check your understanding
Practise this
Hands-on work that uses this topic.
Build Your Own X
Weekly Challenges
See it in real code
Guided tours through the source of real libraries that rely on it.