Updating state lets your app remember and show new information when things change. It helps your app respond to user actions or data updates.
Updating state in React
const [state, setState] = useState(initialValue); // To update state: setState(newValue); // Or update based on previous state: setState(prevState => updatedValue);
Use useState hook to create state in functional components.
Always use the setter function (like setState) to update state, never change state directly.
const [count, setCount] = useState(0); setCount(5);
setCount(prevCount => prevCount + 1);const [text, setText] = useState(''); setText('Hello');
This component shows a number and two buttons. Clicking 'Increase' adds 1 to the number. Clicking 'Decrease' subtracts 1. The state updates and the number on screen changes.
import React, { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <main> <h1>Count: {count}</h1> <button onClick={() => setCount(count + 1)} aria-label="Increase count"> Increase </button> <button onClick={() => setCount(count - 1)} aria-label="Decrease count"> Decrease </button> </main> ); }
State updates are asynchronous, so changes may not happen immediately.
Use the function form of setter when new state depends on old state to avoid bugs.
Always keep state updates pure and avoid side effects inside the setter function.
State holds data that can change in your component.
Use useState hook to create and update state.
Update state with the setter function to make your UI update automatically.
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
