Three Ways React Code Goes Wrong Without Breaking
React rarely stops you from writing code that runs. What it does allow is code that appears to work — and that quietly misbehaves once your data shapes or components change. The three patterns below share that trait: each one functions under a narrow set of conditions and fails in subtle, hard-to-trace ways. Familiarity with hooks is assumed.
Mutating a props object instead of its number
Consider a parent holding a count in state, with a button that increments it, and a child that receives the count and renders it plus five. The child adds five directly to the prop and the demo works. Refactor the state so it holds an object rather than a number — plausible as a component grows and needs to store more fields — and the child adds five to count on that object. Now every click appears to add six.
The cause is value vs. reference semantics. Primitives like numbers, booleans and strings are immutable and passed by value; objects are passed by reference. Assigning an object to a second variable and changing it through that variable also changes the original. When the child modifies a property on the state object, it is editing the very object React later reads when updating state — after the child has already added five.
Avoiding the mutation
For the simple case, skip mutation entirely and express the change in the render function:
function Child({state}){
return <div><p>count + 5 = {state.count + 5} </p></div>
}
When state.count + 5 is reused in several places, or the transformed data must reach several children, the child should clone the incoming prop and transform the clone. Spread syntax into an object literal is one option:
function Child({state}){
const copy = {...state};
return <div><p>count + 5 = {copy.count + 5} </p></div>
}
Nested objects will still reference the originals and need more thorough copying. Serializing to JSON and immediately parsing it back handles most simple object shapes:
JSON.parse(JSON.stringify(myobject))
Data with more exotic types may call for a library — lodash's deep clone, for example, or Immutable.js, whose immutable data structures carry an explicit guarantee that nothing gets mutated behind your back. The immutable Map class can represent the counter's state as well.
Initializing child state from props
Picture a parent whose state holds a count, passing it as a prop to a child that uses it in a useState initializer.
function Parent(){
const [parentCount,setParentCount] = useState(0);
return <div>
<p>Parent count: {parentCount}</p>
<button onClick={()=>setParentCount(c=>c+1)}>Increment Parent</button>
<Child parentCount={parentCount}/>
</div>;
}
function Child({parentCount}){
const [childCount,setChildCount] = useState(parentCount);
return <div>
<p>Child count: {childCount}</p>
<button onClick={()=>setChildCount(c=>c+1)}>Increment Child</button>
</div>;
}
Many developers expect the child's state to be discarded and rebuilt when the prop changes, since the component is just a function. It isn't. State wins over the incoming prop: after the child's state is set on first render, it is independent of any props. React keeps component state in the tree per component, and only unmounting discards it — new props do not. This is the derived-state anti-pattern, and it costs the component its single source of truth.
Resetting a child on demand with key
There are legitimate cases for pushing draft state down — for instance as a performance optimization, so that keystrokes in a text input don't re-render the parent. A daily gratitude list makes a good example: a parent holds an array of five statements, and a child owns the input draft for each, pre-filled with an example string passed as a prop.
// These are going to be our default values for each of the five notes
// To give the user an idea of what they might write
const ideaList = ["I'm thankful for my friends",
"I'm thankful for my family",
"I'm thankful for my health",
"I'm thankful for my hobbies",
"I'm thankful for CSS Tricks Articles"]
const maxStatements = 5;
function Parent(){
const [list,setList] = useState([]);
// Handler function for when the statement is completed
// Sets state providing a new array combining the current list and the new item
function onStatementComplete(payload){
setList(list=>[...list,payload]);
}
// Function to reset the list back to an empty array
function reset(){
setList([]);
}
return <div>
<h1>Your thankful list</h1>
<p>A five point list of things you're thankful for:</p>
{/* First we list the statements that have been completed*/}
{list.map((item,index)=>{return <p>Item {index+1}: {item}</p>})}
{/* If the length of the list is under our max statements length, we render
the statement form for the user to enter a new statement.
We grab an example statement from the idealist and pass down the onStatementComplete function.
Note: This implementation won't work as expected*/}
{list.length<maxStatements ?
<StatementForm initialStatement={ideaList[list.length]} onStatementComplete={onStatementComplete}/>
:<button onClick={reset}>Reset</button>
}
</div>;
}
// Our child StatementForm component This accepts the example statement for it's initial state and the on complete function
function StatementForm({initialStatement,onStatementComplete}){
// We hold the current state of the input, and set the default using initialStatement prop
const [statement,setStatement] = useState(initialStatement);
return <div>
{/*On submit we prevent default and fire the onStatementComplete function received via props*/}
<form onSubmit={(e)=>{e.preventDefault(); onStatementComplete(statement)}}>
<label htmlFor="statement-input">What are you thankful for today?</label><br/>
{/* Our controlled input below*/}
<input id="statement-input" onChange={(e)=>setStatement(e.target.value)} value={statement} type="text"/>
<input type="submit"/>
</form>
</div>
}
Submitting a completed statement leaves the child still holding the submitted text rather than the next example string, because the child remembers its old state. Detecting prop changes in a useEffect and resetting the state works in some cases, but it breaks when different parts of your data legitimately share the same value — the prop hasn't changed, yet you still need a reset.
The key prop, the same special prop React asks for when rendering lists, gives the parent that control. Changing the key tells React to treat the element as a conceptually different item and construct a fresh instance. Set it to the index about to be filled:
<StatementForm key={list.length} initialStatement={ideaList[list.length]} onStatementComplte={onStatementComplete}/>
With that single change, each submission throws away the old child state and the example statement appears. One changed prop, a completely different behavior.
Closures that capture old state
Stale closures are a common hooks problem and show up wherever a function keeps a reference to state from an earlier render. Inside useEffect, doing anything asynchronous invites them. An interval that increments a count each second, set up on first render with an empty dependency array so React doesn't restart it, is a standard example:
function Counter() {
let [count, setCount] = useState(0);
useEffect(() => {
let id = setInterval(() => {
setCount(count + 1);
}, 1000);
return () => clearInterval(id);
},[]);
return <h1>{count}</h1>;
}
The count reaches one and freezes. Per the MDN definition, "a closure is the combination of a function and the lexical environment within which that function was declared," and the environment includes local variables in scope at the time of creation. The counter function is declared once, on the first render, where count is zero; it never gets redeclared. Each tick calls a function that starts from zero and returns one.
The dependency array governs more than firing: it also redeclares the closure when a dependency changes, keeping it clear of stale state and props. Omitting the array would have redeclared the closure — but at the cost of restarting the interval on every render. A lint rule exists precisely to catch missing dependencies.
Functional updates
The simplest fix drops the state variable and passes a function into the setter:
function Counter() {
let [count, setCount] = useState(0);
useEffect(() => {
let id = setInterval(() => {
setCount(prevCount => prevCount+ 1);
}, 1000);
return () => clearInterval(id);
},[]);
return <h1>{count}</h1>;
}
An alternative keeps the count in a mutable reference via useRef:
function Counter() {
let [count, setCount] = useState(0);
const countRef = useRef(count)
function updateCount(newCount){
setCount(newCount);
countRef.current = newCount;
}
useEffect(() => {
let id = setInterval(() => {
updateCount(countRef.current + 1);
}, 1000);
return () => clearInterval(id);
},[]);
return <h1>{count}</h1>;
}
ReactDOM.render(<Counter/>,document.getElementById("root"))
Dan Abramov's useInterval article takes a third route, placing the entire closure in a ref rather than the count.
When the closure lives in a DOM event handler
Stale closures are not confined to useEffect. Take a scroll progress bar that, as the user scrolls, grows wider across the screen, shifts from transparent toward opaque, and offers a button that randomizes its color. The bar lives outside the React tree and is updated by the event handler:
<body>
<div id="root"></div>
<div id="progress"></div>
</body>
function Scroller(){
// We'll hold the scroll position in one state
const [scrollPosition, setScrollPosition] = useState(window.scrollY);
// And the current color in another
const [color,setColor] = useState({r:200,g:100,b:100});
// We assign out scroll listener on the first render
useEffect(()=>{
document.addEventListener("scroll",handleScroll);
return ()=>{document.removeEventListener("scroll",handleScroll);}
},[]);
// A function to generate a random color. To make sure the contrast is strong enough
// each value has a minimum value of 100
function onColorChange(){
setColor({r:100+Math.random()*155,g:100+Math.random()*155,b:100+Math.random()*155});
}
// This function gets called on the scroll event
function handleScroll(e){
// First we get the value of how far down we've scrolled
const scrollDistance = document.body.scrollTop || document.documentElement.scrollTop;
// Now we grab the height of the entire document
const documentHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
// And use these two values to figure out how far down the document we are
const percentAlong = (scrollDistance / documentHeight);
// And use these two values to figure out how far down the document we are
const progress = document.getElementById("progress");
progress.style.width = `${percentAlong*100}%`;
// Here's where our bug is. Resetting the color here will mean the color will always
// be using the original state and never get updated
progress.style.backgroundColor = `rgba(${color.r},${color.g},${color.b},${percentAlong})`;
setScrollPosition(percentAlong);
}
return <div className="scroller" style={{backgroundColor:`rgb(${color.r},${color.g},${color.b})`}}>
<button onClick={onColorChange}>Change color</button>
<span class="percent">{Math.round(scrollPosition* 100)}%</span>
</div>
}
ReactDOM.render(<Scroller/>,document.getElementById("root"))
Width and opacity respond to scrolling, but the color button does nothing. State-changed color is read through a closure that is never redeclared, so the handler only ever sees the initial value. Closures that call external APIs using state or props are prone to the same grief.
Holding the color in a ref is one fix:
const [color,setColor] = useState({r:200,g:100,b:100});
const colorRef = useRef(color);
function onColorChange(){
const newColor = {r:100+Math.random()*155,g:100+Math.random()*155,b:100+Math.random()*155};
setColor(newColor);
colorRef.current=newColor;
progress.style.backgroundColor = `rgba(${newColor.r},${newColor.g},${newColor.b},${scrollPosition})`;
}
That works, but it means fighting the framework to keep an element out of the tree. Since this is only the DOM API, the cleaner fix is to render the progress bar inside the React tree as JSX so it reads component state directly, leaving the event handler to do nothing but update state:
function Scroller(){
const [scrollPosition, setScrollPosition] = useState(window.scrollY);
const [color,setColor] = useState({r:200,g:100,b:100});
useEffect(()=>{
document.addEventListener("scroll",handleScroll);
return ()=>{document.removeEventListener("scroll",handleScroll);}
},[]);
function onColorChange(){
const newColor = {r:100+Math.random()*155,g:100+Math.random()*155,b:100+Math.random()*155};
setColor(newColor);
}
function handleScroll(e){
const scrollDistance = document.body.scrollTop || document.documentElement.scrollTop;
const documentHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
const percentAlong = (scrollDistance / documentHeight);
setScrollPosition(percentAlong);
}
return <>
<div class="progress" id="progress"
style={{backgroundColor:`rgba(${color.r},${color.g},${color.b},${scrollPosition})`,width: `${scrollPosition*100}%`}}></div>
<div className="scroller" style={{backgroundColor:`rgb(${color.r},${color.g},${color.b})`}}>
<button onClick={onColorChange}>Change color</button>
<span class="percent">{Math.round(scrollPosition * 100)}%</span>
</div>
</>
}
The stale handler is impossible now, and the progress bar is a self-contained, declarative component.
Closing thought
Happy-path counters don't reveal these subtleties. The protection is a solid mental model of how the APIs behave, which is what the React docs, MDN's closures documentation, and blogs from the React core team and its community are there to build.



