Sub topic 2
What Makes a Value Reactive
This chapter assumes you can write function components with props and useState, that you have used useEffect with a cleanup function and a dependency array, and that you know how JavaScript closures capture variables. The previous chapter separated event handlers, which run because the user did something, from Effects, which run to keep the component in sync with something outside React. This chapter defines the term that governs Effects: the reactive value. You need it to tell which parts of an Effect should re-run when data changes and which parts should not.
The Definition
A reactive value is any value declared inside the component body that can be different from one render to the next. That covers three groups:
- Props, because the parent can pass new ones on any render.
- State, because calling a setter schedules a render with a new value.
- Anything computed from props or state during render, such as derived variables and functions declared in the component body.
The test is whether a re-render could produce a different value, not whether the value is likely to change. A prop that happens to stay the same for the whole session is still reactive, because nothing in the component's code guarantees it will stay the same.
Values declared outside the component are not reactive. A module-level constant is created once when the module loads, and rendering never touches it again.
import { useState, useRef } from 'react';
const serverUrl = 'https://localhost:1234'; // not reactive: module scope
function ChatRoom({ roomId, theme }) { // roomId, theme: reactive (props)
const [message, setMessage] = useState(''); // message: reactive (state)
const isLong = message.length > 100; // isLong: reactive (derived from state)
const label = `Room ${roomId}`; // label: reactive (derived from a prop)
const inputRef = useRef(null); // inputRef: stable object, not reactive
function formatMessage() { // formatMessage: reactive (reads message)
return `[${roomId}] ${message}`;
}
return (
<div className={theme}>
<h2>{label}</h2>
<input
ref={inputRef}
value={message}
onChange={(e) => setMessage(e.target.value)} // setMessage: stable
/>
{isLong && <p>That is a long message.</p>}
<p>{formatMessage()}</p>
<p>Server: {serverUrl}</p>
</div>
);
}
export default ChatRoom;Why Render Scope Matters
Each render is a separate call to your component function, and each call gets its own local variables. When you write an arrow function or an Effect inside the component, it closes over the variables of the render that created it. The Effect from render 3 sees render 3's roomId. If render 4 has a different roomId, the Effect from render 3 still sees the old one.
This is why React needs to know which values an Effect reads. An Effect is a snapshot of one render's values. When one of those values changes, the snapshot is out of date, and the only way to pick up the new value is to run a new Effect created by a newer render.
import { useState, useEffect } from 'react';
function SnapshotDemo() {
const [count, setCount] = useState(0);
useEffect(() => {
// This closure belongs to one specific render.
const id = setTimeout(() => {
console.log('Effect from the render where count was', count);
}, 2000);
return () => clearTimeout(id);
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
export default SnapshotDemo;Click three times quickly. Each click renders again, cleans up the previous timeout, and schedules a new one. Only the last timeout fires, and it logs 3. If you removed count from the dependency array, the Effect from the first render would be the only one that ever ran, and its closure would hold count as 0 forever.
Values That Look Reactive but Are Not
Some values are declared inside the component yet are guaranteed to be identical on every render. React and the dependency linter treat them as non-reactive.
| Value | Declared where | Reactive? | Why |
|---|---|---|---|
| Prop such as `roomId` | Component parameters | Yes | Parent can pass a new value on any render |
| State such as `message` | `useState` | Yes | Setter triggers a render with a new value |
| Derived variable such as `isLong` | Component body | Yes | Recomputed from reactive values each render |
| Function declared in the body | Component body | Yes | New function object every render, and it may read reactive values |
| State setter such as `setMessage` | `useState` | No | React guarantees the same function identity |
| `dispatch` from `useReducer` | `useReducer` | No | Same identity guarantee as setters |
| Ref object from `useRef` | `useRef` | No | Same object on every render |
| `ref.current` | Mutated anywhere | No, and not trackable | Changing it does not trigger a render |
| Module-level constant | Outside the component | No | Created once at module load |
| Global mutable value such as `location.pathname` | Browser | Not trackable | Changes without React knowing |
The last two rows need a closer look.
Refs Hold Values React Does Not Track
ref.current can change, but assigning to it does not cause a render. React cannot notice the change, so listing ref.current as a dependency would not work: the Effect re-runs only if something else causes a render, and then it compares against whatever current happened to be. A ref is a way to keep a value outside the reactive system on purpose. Later chapters return to refs as an alternative to Effect Events and explain why they are usually the weaker choice.
External Mutable Values
location.pathname, window.innerWidth, or a field on a mutable global object can change at any time without a render. They cannot be dependencies for the same reason ref.current cannot. If your component must react to such a value, subscribe to it with useSyncExternalStore. That hook turns the external value into a reactive value by triggering a render when it changes.
A Decision Flow for Any Value
Reactive Logic and Non-Reactive Logic
Values are reactive or not. Code is also reactive or not, depending on why it runs.
- Reactive logic should run again whenever the values it reads change. Code inside an Effect is reactive: the Effect exists to stay in sync with its inputs.
- Non-reactive logic runs because of a specific occurrence, such as a click or a connection succeeding, and should not run again just because a value it reads has changed. Code inside an event handler is non-reactive: clicking "Send" sends the current message once, and editing the message afterward does not send it again.
Event handlers can read reactive values freely, because nothing re-runs them when those values change. They read whatever the latest render gave them at the moment the user acts.
import { useState, useEffect } from 'react';
const serverUrl = 'https://localhost:1234';
function createConnection(url, roomId) {
return {
connect() { console.log(`Connecting to ${roomId} at ${url}`); },
disconnect() { console.log(`Disconnected from ${roomId}`); },
};
}
function sendMessage(roomId, text) {
console.log(`Sent to ${roomId}: ${text}`);
}
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
// Reactive logic: must re-run when roomId changes.
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]); // serverUrl is module-level, so it is not listed
// Non-reactive logic: runs only when the user clicks.
function handleSend() {
sendMessage(roomId, message);
setMessage('');
}
return (
<>
<input value={message} onChange={(e) => setMessage(e.target.value)} />
<button onClick={handleSend}>Send</button>
</>
);
}
export default ChatRoom;handleSend reads roomId and message, both reactive, but it is not reactive logic. Typing in the input renders the component again and creates a new handleSend, but nothing calls it until the next click. The Effect reads only roomId, so only roomId belongs in its array. message never appears there because the Effect never reads it.
Common Mistakes When Classifying Values
Treating "rarely changes" as "not reactive." A theme prop that users toggle once a week is still a prop. If an Effect reads it, the linter requires it as a dependency.
Forgetting that functions in the body are reactive. A helper declared inside the component is a new object on every render. If an Effect calls it, the Effect depends on it and will re-run on every render. Move the helper inside the Effect, or out of the component if it reads no reactive values.
Assuming objects created during render are stable. const options = { roomId } builds a new object each render. Even when roomId stays the same, options fails the Object.is comparison, so an Effect that depends on options re-runs every time.
Adding setters or ref objects "just in case." Listing them does no harm, since their identity never changes, but they add noise to the array. The linter does not require them when they come directly from useState, useReducer, or useRef in the same component. If they arrive as props, the linter cannot know they are stable and treats them as reactive.
The problem this tutorial solves comes from mixing the two kinds of logic. An Effect can contain mostly reactive logic plus a small piece that only reads a value without needing to react to it. The language has no way to mark that piece as non-reactive, so the whole Effect re-runs. The next chapters show how dependencies drive that re-run and why it causes trouble.
Exercise
In the component below, which names are reactive values? const API = '/api'; function Profile({ userId }) { const [tab, setTab] = useState('posts'); const cacheRef = useRef(new Map()); const url = API + '/users/' + userId + '?tab=' + tab; ... }
Show answer
userId (prop), tab (state), and url (derived from userId and tab) are reactive. API is a module-level constant. setTab and cacheRef are stable identities from hooks, so neither is reactive. cacheRef.current can change but React cannot track it.
Exercise
A teammate writes useEffect(() => { track(window.location.pathname); }, [window.location.pathname]); and says it works. Why is this unreliable, and what should they use instead?
Show answer
window.location.pathname is an external mutable value. Changing it does not trigger a React render, and React compares dependencies only during a render, so the Effect re-runs only when some unrelated render happens to occur. Subscribe with useSyncExternalStore, or use the router's location hook, which turns the pathname into a reactive value.
Exercise
An event handler reads message and roomId and calls sendMessage(roomId, message). Why doesn't editing message cause the message to be sent again, even though message is reactive?
Show answer
Event handlers contain non-reactive logic. They run only when their event fires. Each render creates a new handler that closes over the latest values, but React calls it only on the next click. Reading a reactive value does not make code reactive. Only Effects re-run in response to changes in the values they read.