0
0
Reactframework~10 mins

Updating state in React - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to update the state using the setter function.

React
const [count, setCount] = useState(0);

function increment() {
  setCount([1]);
}
Drag options to blanks, or click blank then click option'
Acount * 2
Bcount - 1
C0
Dcount + 1
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the old count without change.
Using subtraction instead of addition.
2fill in blank
medium

Complete the code to update state based on the previous state value.

React
const [likes, setLikes] = useState(0);

function addLike() {
  setLikes([1] => [1] + 1);
}
Drag options to blanks, or click blank then click option'
Aprev
Bcount
Clikes
Dstate
Attempts:
3 left
💡 Hint
Common Mistakes
Using the state variable directly inside the setter function.
Forgetting to return the new state value.
3fill in blank
hard

Fix the error in the state update to correctly toggle a boolean value.

React
const [isOn, setIsOn] = useState(false);

function toggle() {
  setIsOn([1] => ![1]);
}
Drag options to blanks, or click blank then click option'
Aprev
Bstate
CisOn
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using the state variable directly inside the setter function.
Not negating the previous state value.
4fill in blank
hard

Fill both blanks to update an object state property correctly.

React
const [user, setUser] = useState({ name: 'Alice', age: 25 });

function updateName(newName) {
  setUser({ ...user, [1]: [2] });
}
Drag options to blanks, or click blank then click option'
Aname
BnewName
Cage
Duser
Attempts:
3 left
💡 Hint
Common Mistakes
Overwriting the entire user object without spreading.
Using the wrong property name.
5fill in blank
hard

Fill both blanks to update a nested state object immutably.

React
const [profile, setProfile] = useState({
  user: { name: 'Bob', details: { age: 30, city: 'NY' } }
});

function updateCity(newCity) {
  setProfile({
    ...profile,
    user: {
      ...profile.user,
      details: { ...profile.user.details, [1]: [2] }
    }
  });
}
Drag options to blanks, or click blank then click option'
Acity
BnewCity
Cage
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Not spreading nested objects causing loss of data.
Updating the wrong property.