Fix Bug: Component displays stale data after state update when using React.memo or useMemo in React
This bug occurs when a memoized component or callback captures an outdated variable in a closure because its dependency array is missing the variable that changed. React skips re-rendering the memoized component since its deps appear unchanged. Fix it by including all referenced variables in the useMemo, useCallback, or React.memo comparison dependency arrays.
Reading the Stack Trace
Here's what each line means:
- at ChatMessage (webpack-internal:///./src/components/ChatMessage.tsx:14:5): ChatMessage uses a stale closure value captured when the component was last rendered, not the current value.
- at MemoizedChatMessage (webpack-internal:///./src/components/ChatMessage.tsx:28:20): React.memo wraps ChatMessage and skips re-rendering because the dependency comparison does not account for the changed value.
- at updateFunctionComponent (node_modules/react-dom/cjs/react-dom.development.js:19588:20): React is updating the parent but the memoized child is skipped, leaving it with outdated data.
Common Causes
1. Missing dependency in useCallback
A useCallback hook omits a state variable from its dependency array, so the callback captures the initial value and never updates.
export default function ChatWindow({ userId }) {
const [messages, setMessages] = useState([]);
const handleDelete = useCallback((id: string) => {
setMessages(messages.filter(m => m.id !== id));
}, []); // Missing `messages` dependency
return messages.map(m => (
<ChatMessage key={m.id} message={m} onDelete={handleDelete} />
));
}
2. Custom React.memo comparison ignoring key props
A custom areEqual function passed to React.memo does not compare all relevant props, causing the component to skip updates.
const ChatMessage = React.memo(
({ message, onDelete }) => (
<div onClick={() => onDelete(message.id)}>{message.text}</div>
),
(prev, next) => prev.message.id === next.message.id
// Missing comparison of message.text and onDelete
);
3. useMemo with stale reference
A useMemo computation references a variable that is not in the dependency array, so it returns a cached result based on outdated data.
export default function Analytics({ data, filter }) {
const filtered = useMemo(
() => data.filter(item => item.category === filter),
[data] // Missing `filter` dependency
);
return <Chart data={filtered} />;
}
The Fix
Use the functional updater form of setMessages (prev => prev.filter(...)) instead of referencing the messages state variable directly. This removes the dependency on messages entirely, so the callback never goes stale and useCallback can safely keep an empty dependency array.
export default function ChatWindow({ userId }) {
const [messages, setMessages] = useState([]);
const handleDelete = useCallback((id: string) => {
setMessages(messages.filter(m => m.id !== id));
}, []);
return messages.map(m => (
<ChatMessage key={m.id} message={m} onDelete={handleDelete} />
));
}
export default function ChatWindow({ userId }) {
const [messages, setMessages] = useState([]);
const handleDelete = useCallback((id: string) => {
setMessages(prev => prev.filter(m => m.id !== id));
}, []);
return messages.map(m => (
<ChatMessage key={m.id} message={m} onDelete={handleDelete} />
));
}
Testing the Fix
import { render, screen, fireEvent } from '@testing-library/react';
import ChatWindow from './ChatWindow';
describe('ChatWindow', () => {
it('renders messages', () => {
render(<ChatWindow userId="user1" />);
// Component should render without errors
expect(document.querySelector('div')).toBeInTheDocument();
});
it('deletes a message without stale closure bug', async () => {
const { rerender } = render(<ChatWindow userId="user1" />);
// Simulate adding messages and deleting one
// The delete handler should use current state, not stale state
rerender(<ChatWindow userId="user1" />);
expect(document.querySelector('div')).toBeInTheDocument();
});
it('handles rapid deletions correctly', () => {
render(<ChatWindow userId="user1" />);
// Multiple rapid deletions should each operate on the latest state
expect(document.querySelector('div')).toBeInTheDocument();
});
});
Run your tests:
npm test
Pushing Through CI/CD
git checkout -b fix/react-memo-stale-closure,git add src/components/ChatWindow.tsx src/components/__tests__/ChatWindow.test.tsx,git commit -m "fix: use functional updater in useCallback to prevent stale closure",git push origin fix/react-memo-stale-closure
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test -- --coverage
- run: npm run build
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
import { initBugStack } from 'bugstack-sdk'
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the test suite locally to confirm memoized components reflect current state.
- Open a pull request with the functional updater fix.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify the component displays current data in staging.
Frequently Asked Questions
BugStack validates that memoized components reflect current state after updates, runs your test suite, and checks for stale closure patterns across the codebase before marking it safe.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
The react-hooks/exhaustive-deps ESLint rule warns you when a hook dependency array is missing variables that are used inside the hook, catching most stale closure bugs at lint time.
Avoid React.memo for components that almost always receive different props, since the shallow comparison adds overhead without preventing re-renders. Profile before optimizing.