State bugs: mutation, stale snapshots and duplication
Turn a vague failure report into a reproduction, isolate the cause, form and falsify hypotheses, instrument the code, fix async and state bugs, lock the fix behind a regression test and review changes for real trade-offs.
What you will be able to do
#- Recognise a state bug caused by in-place mutation.
- Recognise a stale snapshot captured by a closure or callback.
- Remove duplicated state by deriving one value from another.
Overview
#State bugs come from the gap between what you think is stored and what is actually stored. The three common shapes are mutation, stale snapshots and duplicated state.
Mutation is the first. If code changes an object in place, every holder of that reference sees the change, including code that expected the old value.
function addItem(cart, item) {
cart.items.push(item);
return cart;
}
The caller's cart is now different even though the function was supposed to return a new one. A pure update returns a new object.
function addItem(cart, item) {
return { ...cart, items: [...cart.items, item] };
}
Stale snapshots are the second shape. A closure or a captured value keeps the value from the time it was created, not the latest value. This is common with timers, event handlers and async callbacks.
function useCounter() {
let count = 0;
const increment = () => {
count += 1;
render(count);
};
return increment;
}
If render schedules work that reads count later, it may read a newer value than intended. The fix is to pass the value explicitly rather than read the shared binding later.
Duplicated state is the third shape. When the same fact is stored twice, the two copies drift. Derive one from the other instead of storing both.
// duplicated: fullName can disagree with first and last
const state = { first: 'Ada', last: 'Lovelace', fullName: 'Ada Lovelace' };
// derived: one source of truth
const fullName = `${state.first} ${state.last}`;
When a state bug appears, ask three questions: is anything mutated in place, is any value read after the moment it was captured, and is any fact stored twice.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Debug
addItem mutates the caller's cart. Fix it so the original cart is unchanged and a new cart is returned.
starter.javascriptfunction addItem(cart, item) { cart.items.push(item); return cart; }Reveal the reference answer
reference.javascriptfunction addItem(cart, item) { return { ...cart, items: [...cart.items, item] }; }Authored expected output: The original cart.items length is unchanged; the returned cart contains the new item.
The original pushes into the shared array, so the caller and the return value point at the same mutated object. Spreading the cart and its items produces a new object and a new array.
Exercise 2Predict
A component reads a count inside a setTimeout callback and always logs the value from the first render. What is the cause?
Common misconceptions
#- Returning the same object after changing it is equivalent to returning a new one.
- A closure always reads the latest value of the variable it captured.
Follow-up practice
#- debugging-review-07-async-bugs
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.