What if your app could update itself perfectly every time without you lifting a finger?
Why Updating state in React? - Purpose & Use Cases
Imagine you have a web page with a button that changes a number on the screen. Every time you click, you have to find the number in the HTML and change it manually using JavaScript.
Manually changing the number means writing extra code to find the element, update it, and keep track of the current value. It's easy to forget to update the right place or cause bugs if multiple parts depend on that number.
Updating state in React lets you change data in one place. React automatically updates the screen for you, so you don't have to touch the HTML directly. This keeps your code simple and reliable.
const countElement = document.getElementById('count'); countElement.textContent = Number(countElement.textContent) + 1;
const [count, setCount] = React.useState(0); setCount(count + 1);
This makes your app respond instantly and correctly to user actions without messy manual updates.
Think of a shopping cart where the total price updates every time you add or remove an item. React state updates keep the total accurate and the UI smooth.
Manual updates are slow and error-prone.
React state updates automate UI changes.
This leads to cleaner, easier-to-maintain code.
Practice
count using the useState hook in React?Solution
Step 1: Understand how useState works
TheuseStatehook returns a pair: the current state and a function to update it.Step 2: Use the setter function to update state
To change the state, you must call the setter function with the new value, e.g.,setCount(newValue).Final Answer:
Call the setter function likesetCount(newValue)to update the state. -> Option AQuick Check:
Update state with setter function = A [OK]
- Trying to assign state variable directly
- Using class component syntax in functional components
- Returning new value instead of calling setter
name with value "John" using useState?Solution
Step 1: Recall useState returns an array
TheuseStatehook returns an array with two elements: the state variable and the setter function.Step 2: Use array destructuring to get both
Use array destructuring syntax:const [name, setName] = useState('John');to get both the value and setter.Final Answer:
const [name, setName] = useState('John'); -> Option CQuick Check:
useState returns [state, setter] array = B [OK]
- Assigning useState result directly without destructuring
- Using object destructuring instead of array
- Only taking the first element without setter
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
setCount(count + 1);
};
return (
<>
{count}
Increment
</>
);
}Solution
Step 1: Understand state updates are asynchronous and batched
BothsetCount(count + 1)calls use the samecountvalue (0) because state updates are batched.Step 2: Result after both calls
Both calls set count to 1, so after clicking,countbecomes 1, not 2.Final Answer:
1 -> Option DQuick Check:
Multiple setState with same value = C [OK]
- Assuming count increments twice immediately
- Expecting count to be 2 after two calls
- Ignoring React's batching behavior
import React, { useState } from 'react';
function Toggle() {
const [isOn, setIsOn] = useState(false);
function handleClick() {
isOn = !isOn;
}
return {isOn ? 'ON' : 'OFF'};
}Solution
Step 1: Check how state is updated
The code tries to assignisOn = !isOn;directly, which is not allowed for state variables.Step 2: Correct way to update state
State must be updated by calling the setter function:setIsOn(!isOn);.Final Answer:
Directly assigning to state variable instead of using setter. -> Option BQuick Check:
Update state only via setter function = D [OK]
- Assigning state variable directly
- Forgetting to call setter function
- Confusing state variable with setter
user with a new age property without losing other properties. Which is the correct way to update state using setUser?const [user, setUser] = useState({ name: 'Alice', age: 25 });
// Update age to 26Solution
Step 1: Preserve existing properties when updating state object
To update one property without losing others, copy previous state using spread syntax.Step 2: Use functional update form to get latest state
UsesetUser(prevUser => ({ ...prevUser, age: 26 }))to merge old properties with new age.Final Answer:
setUser(prevUser => ({ ...prevUser, age: 26 })); -> Option AQuick Check:
Use spread and functional update to merge state = A [OK]
- Replacing whole object losing other properties
- Mutating state directly instead of returning new object
- Not using functional update when depending on previous state
Ready to prove it?
Pass the test and this pattern moves unknown
