React Bug: Incorrect State Update with Hooks

🚨 React Bug That Looks Correct… But Isn’t 👀 What’s wrong with this code? function App() { const [user, setUser] = React.useState({ name: "Suman", age: 22 }); const updateAge = () => { user.age = 23; setUser(user); }; return ( <> <button onClick={updateAge}>Update Age</button> <div>{user.age}</div> </> ); } At first glance, everything looks fine. But the UI doesn’t behave as expected. 👉 Why does this happen? 👉 How would you fix it? Small bug… but very common in real projects 👀 #ReactJS #FrontendInterview #JavaScript #ReactHooks #FrontendDeveloper #ProductBasedCompany

React state updates must be immutable. In this example, the object is mutated directly (user.age = 23) and the same reference is passed back to setUser, so React doesn’t detect a change and may skip re-rendering. The fix is to create a new object using the spread operator: setUser(prev => ({ ...prev, age: 23 })), which ensures React sees a new reference and updates the UI.

function App() { const [user, setUser] = React.useState({ name: "Suman", age: 22 }); const updateAge = () => { setUser(prev => ({ ...prev, age: 23 })); }; return ( <> <button onClick={updateAge}>Update Age</button> <div>{user.age}</div> </> );}

Like
Reply

user.age = 23; setUser(user); Issue 👆🏻👆🏻 Here mutating existing state object directly n passing same reference to setUser. user === user // true shallow comparison , so nothing changed , so no re-render Fix:- const updateAge = () => { setUser(prevUser => ({ ...prevUser, age: 23 })); };

React detects state changes when a new object reference is passed to the setter function. It compares the current state value with the new value reference and if they point to the same memory location, React assumes no change has occurred and will not update the component. 

React uses shallow comparison so mutating the same object doesn’t trigger a re-render. setUser({ ...user, age: 23 });

Like
Reply

Classic mutation issue. You’re directly modifying the state object and passing the same reference back to React, so it doesn’t detect a change and won’t re-render properly. State should be treated as immutable. Creating a new object fixes it.

Like
Reply

user.age = 23; // ❌ direct mutation setUser(user);

Like
Reply

Because user. age cannot perform any value updating task it just keep the track of what is updated if we want to really update the age so our function might look like Const updateAge = () =>{ setUser({user, age :23}) }

See more comments

To view or add a comment, sign in

Explore content categories