Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React Basics Understanding State Understanding State Recap

How does the state setter setItems() knows that prevItems refer to the items array?

The state:

const [items, setItems] = useState([ { id: 1, name: "Apples", quantity: 5 }, {id: 2, name: "Bananas",}])

With setItems(items.filter(i => i.id !== id)) it was clear for the setter that the collection to be filtered was the items array - It's clear to me the need of using a callback function as an update function. But with setItems((prevItems) => prevItems.filter(i => i.id !== id)), how does setItems() know that prevItems refer to the items array in the state?

1 Answer

Travis Alstrand
.a{fill-rule:evenodd;}techdegree seal-36
Travis Alstrand
Data Analysis Techdegree Graduate 47,459 Points

Hey Murilo de Melo ! :wave:

With React's useState hook, when you use the functional form of the state updater function, such as setItems((prevItems) => ...), React ensures that the argument passed to the updater function (prevItems in this case) represents the current state at the time the update is being applied.

So when you call setItems((prevItems) => prevItems.filter(i => i.id !== id)), React internally ensures that prevItems holds the current state of the items array. This is part of how React manages state updates and ensures that the state is updated correctly, even in asynchronous scenarios or when state updates are batched.

So, you don't need to explicitly tell setItems what prevItems refers to; React handles that for you. The prevItems argument passed to the updater function is automatically inferred to represent the current state of the items array. This ensures that you're working with the most up-to-date state when updating it. :smiley: