ReactHard

What is effect tearing?

Tearing is a visual inconsistency where different parts of the UI show different versions of the same data during a single render. It can happen with concurrent rendering when a component reads from an external mutable store that changes while React has paused rendering. useSyncExternalStore (React 18) prevents it.

How tearing happens

  1. React starts a concurrent (interruptible) render, for example inside a transition.
  2. Component A reads store.value (version 1).
  3. React yields to the browser; an event mutates the store to version 2.
  4. React resumes and component B reads version 2.
  5. The committed screen shows A with old data and B with new data: torn.

React state and context cannot tear, because React controls when they change. The risk is with external stores: global variables, custom event emitters, browser APIs, older state libraries that subscribed in effects.

The fix: useSyncExternalStore

useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?):

  • React reads the snapshot during render and checks it again before committing.
  • If the store changed mid-render, React re-renders synchronously so everything is consistent.
  • getServerSnapshot provides the value for SSR and hydration.
  • getSnapshot must return a cached, immutable value (the same reference if unchanged), or React loops.

Library support

Redux (useSelector), Zustand, Jotai, Valtio and TanStack Store use useSyncExternalStore internally. When you write your own store or subscribe to browser APIs (online status, media queries, localStorage across tabs), use it too.

Naming

Some call it "tearing" or "UI tearing"; "effect tearing" refers to stores read in effects or render without synchronization.

Code example

tsx
1import { useSyncExternalStore } from "react";
2
3// A tiny external store
4let state = { temperature: 21 };
5const listeners = new Set<() => void>();
6
7export const weatherStore = {
8 set(temperature: number) {
9 state = { temperature }; // new immutable snapshot
10 listeners.forEach((l) => l());
11 },
12 subscribe(l: () => void) {
13 listeners.add(l);
14 return () => listeners.delete(l);
15 },
16 getSnapshot: () => state, // same reference until it changes
17};
18
19// Tear-free read: React guarantees every component sees the same snapshot per render
20function useWeather() {
21 return useSyncExternalStore(weatherStore.subscribe, weatherStore.getSnapshot, weatherStore.getSnapshot);
22}
23
24export function Thermometer() {
25 const { temperature } = useWeather();
26 return <p>{temperature}°C</p>;
27}
28
29export function Advice() {
30 const { temperature } = useWeather();
31 return <p>{temperature > 25 ? "Wear shorts" : "Bring a jacket"}</p>;
32}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app