While working at PuppyAgent, an early-stage startup, I was helping develop a SaaS application that combined a React Flow workflow engine with retrieval-augmented generation (RAG). The workflow nodes were repeatedly re-rendering, and the editor became noticeably sluggish. That practical problem led me back to some basic React questions: what happens when state changes, which work belongs in an Effect, and why does development sometimes appear to run the same code twice?
This article develops the state and Effect side of those notes. The companion article, how to reduce unnecessary re-renders in React, compares refs, state ownership, subscriptions, and memoization.
The examples use a workflow editor as their setting. They are small teaching examples, rather than copies of PuppyAgent's implementation or a record of a particular production fix. They use APIs available in React 18; they do not depend on newer compiler optimizations.
State belongs to a render
Suppose a node configuration panel keeps a revision counter:
import { useState } from 'react';
export function RevisionCounter() {
const [revision, setRevision] = useState(0);
function handleEdit() {
setRevision(revision + 1);
console.log(revision); // On the first click, this still logs 0.
}
return <button onClick={handleEdit}>Revision {revision}</button>;
}
The setter schedules a new state value. It does not rewrite the revision variable captured by this invocation of handleEdit. The next render receives the new value and creates a handler using that render's snapshot.1
My original notes quoted the class component documentation:
Calling
setStatedoes not change the current state in the already executing code:— React, Component, “setState,” Pitfall.2
The same practical warning applies to Hook state, although the APIs are different. Calling a setter is also not a promise-based operation: await setRevision(...) is not a way to wait for React to commit an update.3
What if the next line needs the new value? In the Save handler below, I trim the label once, pass the resulting nextConfig to the setter, and pass that same object to onSave. The click handler already has the value it needs.
Follow one click from the handler to the DOM
For the revision button above, start with both the on-screen label and the handler's captured value at zero. Assume a mounted component, a changed value, and an update that reaches commit. The steps explain why the old value can be logged even though the next paint shows the new one.4
| Stage | What happens to this revision |
|---|---|
| Event | The handler reads zero and asks React to set the revision to one. Local variables in this invocation still hold the old snapshot. |
| Render | React calls the component with the pending state. Its returned button now describes the label “1”. React can restart or discard render work, so render must be pure. |
| Commit | React applies the needed change to the DOM. Code that needs the committed DOM can now observe the new label. |
| Effect | If an Effect depends on the revision, React runs the previous cleanup when applicable and the new setup for the committed value. Its ordering relative to browser paint can vary. |
What appealed to me about refs was the cost of a write. An event handler can keep its last request ID in lastRequest.current for the next handler to read. Writing the ID survives the next render and schedules no render of its own. If I want the ID to appear on screen, I put it in state so React knows to update the label.5
A DOM ref raises a separate question for a reusable canvas component. If a node's name field focuses its input on entering edit mode, I would keep the ref inside the field. The surrounding canvas can lay out the field without knowing which element receives focus. If a parent toolbar also needs to focus it, the field can expose a small focus() handle. In React 18, forwardRef lets the function component receive the parent's ref, and useImperativeHandle defines what the parent can call. React attaches DOM refs during commit.56
A component unmounts when React removes it from the UI. Akhtar gives conditional rendering as one way this can happen.7 Imagine the canvas shows a properties panel only while a node is selected. Clearing the selection unmounts the panel even though the editor stays open. When React removes the panel’s input, it clears the ref that pointed to it.5
Queue updates that depend on previous state
Consider these two handlers inside a counter component:
function incrementThreeTimesFromSnapshot() {
setRevision(revision + 1);
setRevision(revision + 1);
setRevision(revision + 1);
}
function incrementThreeTimesFromPendingState() {
setRevision(previous => previous + 1);
setRevision(previous => previous + 1);
setRevision(previous => previous + 1);
}
Starting at zero, the first handler queues the replacement value 1 three times. The second queues three transformations: 0 → 1 → 2 → 3. Each updater receives the result of the preceding queued update.8
Functional updates are useful when the next value depends on the pending state. They are not needed for every assignment: selecting a node by its known ID can simply call setSelectedNodeId(id).
Keep updater functions pure. A network request inside setNodes(previous => ...) ties an external action to React's evaluation of an update. Compute the next state there; perform the external action in the appropriate event handler or synchronization logic.
Batching is broader than the old FAQ suggests
The legacy FAQ collected in my notes described batching inside event handlers and anticipated broader batching in future versions.9 That was historical guidance. With React 18's createRoot, automatic batching also covers updates originating in promises, timers, and native event handlers.10
Batching lets React process multiple updates together. It does not make state a mutable local variable, and it does not combine every unrelated user action into one update. Separate intentional interactions, such as successive clicks, still need to be handled correctly.8
In a workflow editor, batching can reduce intermediate work when one interaction updates several pieces of state. It cannot make an expensive node component cheap or fix an unnecessarily broad subscription. Those are separate questions for the performance article.
The class callback was not removed
One of my draft conclusions was wrong: the optional callback to class setState was not deprecated and removed in favor of Hooks. These are different interfaces:
| API | Updating an object | Optional completion callback |
|---|---|---|
this.setState(nextState, callback) | Shallowly merges the update into class state | Supported; runs after the update is committed |
A setter returned by useState | Replaces that state value | No corresponding second argument |
This comparison follows the class and Hook references.23 For a Hook holding an object, preserve fields explicitly when needed, such as setConfig(previous => ({ ...previous, label })).
💡 Tip: JavaScript accepts extra arguments, so calling a Hook setter as
setCount(1, afterUpdate)still queues the update to1. React 18.2 binds two internal arguments before yours, which putsafterUpdateatarguments[3]insidedispatchSetState. The development build checks that slot and logs an error if it finds a function. Both builds ignore the callback. TypeScript can flag the extra argument before the code runs.11
The original investigation included a GitHub issue about a component unmounting before its queued callback ran. The reporter was using React 0.14.7; the discussion is useful historical context, not evidence that React removed the callback API.12
In a later comment, gaearon quoted the documentation's recommendation:
Generally we recommend using
componentDidUpdate()for such logic instead.— gaearon (2016, October 23), quoting the documentation in issue #6320.13
The important boundary is the lifetime of the component and its committed updates. A queued UI callback should not be treated as an independent job guaranteed to finish after that UI disappears. Moving logic into a lifecycle method also does not turn it into such a job.
A DEV Community post in my notes raised a related readability concern: class code could place an update and its callback together, while a Hook-based rewrite might split an event across a handler and an Effect.14 That is a useful question about code organization. The answer depends on why the second operation should run.
Choose between an event and synchronization
An event handler expresses an action: the user clicked Save. An Effect expresses synchronization: while this component is present with these dependencies, keep an external system in step with it.1516
For an explicit Save action, the value being saved can be passed directly:
import { useState } from 'react';
export function NodeSettings({ onSave }) {
const [config, setConfig] = useState({ label: 'Retriever' });
function handleSave() {
const nextConfig = { ...config, label: config.label.trim() };
setConfig(nextConfig);
onSave(nextConfig);
}
return (
<div>
<input
aria-label="Node label"
value={config.label}
onChange={event=> {
const label= event.target.value;
setConfig(previous=> ({ ...previous, label }));
}}
/>
<button onClick={handleSave}>Save</button>
</div>
);
}
Here onSave is an application callback whose caller must provide persistence and error handling. It receives the intended value without waiting for a render. It does not need an Effect that sends a request whenever config changes, which would also run for ordinary typing. Autosave would be a different requirement, with its own timing and cancellation policy.
Nor does every derived value need state and an Effect. If a panel displays the number of configured nodes, calculate that number from the current nodes during rendering. Storing it separately creates another value to synchronize; an expensive calculation can be considered for memoization after measurement.16
An Effect should describe setup and cleanup together
For an actual external subscription, an Effect is appropriate. This hook illustrates a workflow status listener using a browser EventTarget supplied by the application:
import { useEffect } from 'react';
export function useWorkflowEvents(eventBus, workflowId, onStatus) {
useEffect(() => {
function handleStatus(event) {
if (event.detail.workflowId === workflowId) {
onStatus(event.detail.status);
}
}
eventBus.addEventListener('workflow-status', handleStatus);
return () => {
eventBus.removeEventListener('workflow-status', handleStatus);
};
}, [eventBus, workflowId, onStatus]);
}
The example assumes events carry { workflowId, status } in their detail. The bus is created outside rendering or otherwise kept stable. All reactive inputs used by the Effect are listed as dependencies. If onStatus changes identity on every render, the Effect will resubscribe; stabilize it when appropriate instead of hiding that dependency.
How does cleanup find the right listener? Here, the function returned from the Effect can still access the exact handleStatus function passed to addEventListener. Akhtar shows a data source with a different API. Its subscribe method returns a subscription object. The Effect saves that object in a local variable, and the cleanup function calls subscription.unsubscribe() on it.7 In both examples, each cleanup has what it needs to undo its own setup.
Suppose the panel stays open while the user switches workflows. When workflowId changes, React removes the listener for the old workflow before registering the listener for the new one. When the panel unmounts, React runs the current cleanup one last time.17
Why an Effect can appear to run twice
The Stack Overflow question saved in my notes asked why an Effect ran twice despite an empty dependency array.18 An empty array means there are no reactive dependencies that trigger reruns. It does not mean the code can execute only once during the entire lifetime of the application.
With a React 18 createRoot application wrapped in <StrictMode>, development includes an extra initial Effect setup/cleanup check. A correctly implemented subscription can therefore follow this sequence:1019
setup → cleanup → setup
After this sequence, one active subscription should remain. When the component is removed, its cleanup should leave none. A guard that merely suppresses the second setup can conceal a missing cleanup rather than solve it.
The legacy documentation states the scope clearly:
Strict mode checks are run in development mode only; they do not impact the production build.
— React, Strict Mode, introductory note.20
There are two related checks to distinguish. Repeated render-phase work helps reveal impure component bodies and updater functions. Repeated Effect setup and cleanup helps reveal incomplete synchronization logic. Strict Mode does not intentionally invoke every click handler twice.19
It is also not the only reason an Effect might run again. A component can actually unmount and remount, a changed key can reset its identity, or a development refresh can reinitialize it. Investigate the cause instead of assuming every repeated log is the same phenomenon. The placement of Strict Mode and the React version matter when interpreting an exact development trace.
Reducers make state transitions easier to inspect
My notes also asked why Redux reducers should be pure.21 The same discipline is useful with React's useReducer: take state and an action, then return the next state without mutating the input or performing external work.2223
For example, a small node-renaming reducer can preserve unchanged node objects:
export function nodesReducer(nodes, action) {
switch (action.type) {
case 'renamed': {
const target = nodes.find(node => node.id === action.id);
if (!target || target.data.label === action.label) return nodes;
return nodes.map(node =>
node.id === action.id
? { ...node, data: { ...node.data, label: action.label } }
: node
);
}
default:
return nodes;
}
}
The unchanged nodes retain their references, and a no-op returns the original array. Those choices make the transition explicit and help consumers recognize unchanged data. They do not, by themselves, guarantee that every unaffected component will skip rendering.
If an action needs a generated ID, timestamp, or server result, obtain that information outside the reducer and include it in the action. Given the same inputs, the transition remains reproducible. This is useful for tests and debugging without requiring the entire application to be written in a functional style.
For the workflow editor, these distinctions give each operation a place: event handlers describe user actions, reducers describe state transitions, and Effects manage external synchronization. Once those boundaries are clear, the next question is which components actually need to render when a node changes.
References
Footnotes
-
React. (n.d.). State as a snapshot. https://react.dev/learn/state-as-a-snapshot ↩
-
React. (n.d.). Component. “setState,” Pitfall and Parameters. https://react.dev/reference/react/Component#setstate ↩ ↩2
-
React. (n.d.). useState. “set functions” and “Updating objects and arrays in state.” https://react.dev/reference/react/useState ↩ ↩2
-
React. (n.d.). Render and commit and useEffect. React documentation. Applying the render result, Effect timing caveats. ↩
-
React. (n.d.). useRef and Manipulating the DOM with refs. React documentation. Storing a value between renders, when React attaches refs. ↩ ↩2 ↩3
-
Rubets, S. (2022, May 22). React useRef, forwardRef and some problems you may run into working with them. HackerNoon. Textarea focus and forwarding a ref. React. (n.d.). useImperativeHandle. React documentation. Exposing a custom ref handle. ↩
-
Akhtar, A. (2023, March 19). How do functional components handle component unmounting in React? LinkedIn. See the conditional rendering example in paragraph 2 and the subscription in the second code example. ↩ ↩2
-
React. (n.d.). Queueing a series of state updates. https://react.dev/learn/queueing-a-series-of-state-updates ↩ ↩2
-
React. (n.d.). Component state. Legacy documentation, “When is setState asynchronous?” https://legacy.reactjs.org/docs/faq-state.html#when-is-setstate-asynchronous ↩
-
The React Team. (2022, March 29). React v18.0. “New Feature: Automatic Batching” and “New Strict Mode Behaviors.” https://react.dev/blog/2022/03/29/react-v18 ↩ ↩2
-
React contributors. (2022). ReactFiberHooks.new.js (React 18.2.0) [Source code]. GitHub. Binding the setter in
mountStateand checking extra arguments indispatchSetState. ↩ -
fatfisz. (2016, March 23). Document that setState() callback is not guaranteed to be called if component unmounts [Issue #6320]. GitHub. https://github.com/facebook/react/issues/6320 ↩
-
gaearon. (2016, October 23). This doesn't seem like a common confusion so I'm not sure it's worth making the language more complex there [Comment on issue #6320]. GitHub. Quoted documentation passage in comment. https://github.com/facebook/react/issues/6320#issuecomment-255589124 ↩
-
official_dulin. (2022, August 4). Is it a bad design to remove the setState callback? [Discussion post]. DEV Community. https://dev.to/mrdulin/is-it-a-bad-design-to-remove-the-setstate-callback-dm1 ↩
-
React. (n.d.). Synchronizing with Effects. “What are Effects and how are they different from events?” https://react.dev/learn/synchronizing-with-effects ↩
-
React. (n.d.). You might not need an Effect. https://react.dev/learn/you-might-not-need-an-effect ↩ ↩2
-
React. (n.d.). useEffect. “Parameters.” https://react.dev/reference/react/useEffect#parameters ↩
-
J.Ko. (2020, March 10). useEffect() is called twice even if an empty array is used as an argument [Question and discussion]. Stack Overflow. https://stackoverflow.com/questions/60618844/useeffect-is-called-twice-even-if-an-empty-array-is-used-as-an-argument ↩
-
React. (n.d.). StrictMode. “Fixing bugs found by double rendering in development” and “Fixing bugs found by re-running Effects in development.” https://react.dev/reference/react/StrictMode ↩ ↩2
-
React. (n.d.). Strict Mode. Legacy documentation, introductory note. https://legacy.reactjs.org/docs/strict-mode.html ↩
-
zeroone001. (2019, April 24). 第 62 题:redux 为什么要把 reducer 设计成纯函数 [Question 62: Why should Redux reducers be pure functions?] [Issue #107 and discussion]. GitHub. https://github.com/Advanced-Frontend/Daily-Interview-Question/issues/107 ↩
-
React. (n.d.). useReducer. React documentation. Reference, especially the reducer parameters. ↩
-
Redux. (n.d.). Redux style guide. “Reducers Must Not Have Side Effects.” https://redux.js.org/style-guide/#reducers-must-not-have-side-effects ↩