Skip to content
Advertisement

Using prevState Callback function in UseState react Hook

I have some array of products inside filteredProducts variable and wanted to sort them according to the price and newly added products. When using prevState like this without having { } in the callback function, the code runs fine.

useEffect(() => {
    if(sort === "newest") {
        setFilteredProducts((prevState) => 
            [...prevState].sort((a, b) => a.createdAt - b.createdAt)
        );
    }
    else if (sort === "asc") {
        setFilteredProducts((prevState) => 
            [...prevState].sort((a ,b) => a.price - b.price)
        );
    }
    else {
        setFilteredProducts((prevState) => 
            [...prevState].sort((a, b) => b.price - a.price)
        );
    }
}, [sort]);

But when using { } for the prevState callback function like this

if(sort === "newest") {
        setFilteredProducts((prevState) => {
            [...prevState].sort((a, b) => a.createdAt - b.createdAt)
        });
    }

, it is just throwing error in console.

Advertisement

Answer

When using the brackets you are declaring a function body, and need to return a value, i.e. the next state. Arrow functions without a function body use an implicit (vs explicit) return.

setFilteredProducts((prevState) => {
  return [...prevState].sort((a, b) => a.createdAt - b.createdAt);
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement