Sub topic 2
What Makes a Value Reactive
This chapter assumes you know JavaScript closures, React function components, props, state with useState, and the basics of useEffect. The previous chapter showed that event handlers run in response to specific interactions, while Effects run to keep something in sync. This chapter covers the next question: which values inside a component can change, and so need an Effect to follow them?
Reactive values
A reactive value is any value declared inside the component body that can be different on a later render. React treats three kinds of values as reactive:
- Props, such as
roomIdpassed in by a parent. - State, such as a value from
useState. - Any variable or function declared in the component body, because it is recalculated on every render and may depend on props or state.
Values declared outside the component are not reactive. A module-level constant is created once when the file loads, and no re-render can change it.
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
const serverUrl = 'https://localhost:1234'; // not reactive: module scope
function ChatRoom({ roomId }) { // roomId: reactive (prop)
const [message, setMessage] = useState(''); // message: reactive (state)
const options = { serverUrl, roomId }; // options: reactive (derived in the body)
useEffect(() => {
const connection = createConnection(options.serverUrl, options.roomId);
connection.connect();
return () => connection.disconnect();
}, [options]);
return (
<input value={message} onChange={(e) => setMessage(e.target.value)} />
);
}options is a new object on every render, even when roomId stays the same. It counts as reactive, and because it is a new object each time, this Effect reconnects on every keystroke in the input. That is a common mistake. The fix is to create the object inside the Effect and depend on roomId instead. The next chapter covers dependencies in detail.
Reactive logic versus non-reactive logic
Values are only part of the picture. The code that reads them also falls into one of two categories.
| Where the code runs | Does it react to value changes? | Why |
|---|---|---|
| Event handler | No | It runs only when the user acts, and reads whatever values exist at that moment. |
| Effect body | Yes | React may run it again whenever a reactive value it reads changes. |
| Rendering code | Yes | It runs on every render and produces output from current values. |
Take a "Send" button handler that reads message. It does not need to run again when message changes. It should run once, when the user clicks. An Effect that reads roomId should run again when roomId changes, because the connection must match the room on screen.
Why the distinction matters
An Effect can't pick which of the reactive values it reads to follow. If its code reads a reactive value, that value becomes a dependency. This is usually what you want. Sometimes, though, an Effect reads a value only to use its current contents, such as a theme color for a notification, and you don't want changes to that value to restart the Effect. Later chapters show how useEffectEvent moves that kind of read out of the reactive part of the Effect.
Exercise
In the component below, which of API_ROOT, userId, count, url, and timerRef are reactive?
const APIROOT = '/api';
function Profile({ userId }) {
const [count, setCount] = useState(0);
const url = `${APIROOT}/users/${userId}`;
const timerRef = useRef(null);
// ...
}
Show answer
userId (a prop), count (state), and url (calculated in the component body from a prop) are reactive. API_ROOT is declared at module scope, so it never changes between renders. timerRef is a stable ref object, and changes to timerRef.current do not cause a re-render, so it is not reactive either.
Exercise
A "Save" button handler reads the draft state. Should a change to draft make the save logic run again? Explain why.
Show answer
No. Event handler logic is not reactive. It should run only when the user clicks Save, and at that moment it reads the current draft. Running it again on every edit would save without the user asking.