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![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Murilo de Melo](https://uploads.teamtreehouse.com/production/profile-photos/7952832/micro_39976100_541132026341155_4400611018896572416_n.jpg)
Murilo de Melo
14,456 PointsHow 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](https://uploads.teamtreehouse.com/production/profile-photos/11658224/micro_travis.jpg)
Travis Alstrand
Data Analysis Techdegree Graduate 49,407 PointsHey Murilo de Melo !
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.