简体   繁体   中英

How to use useEffect for a useState variable that has no dependency?

I'm creating a React form that has stores new product list in a local state ie

const [listItem, setListItem] = useState([]);

I have submit handlers where I append new value like-

const handleAddProduct = (data) => {
  setListItem ([...listItem], data)
  console.log('ListItems-', listItem); // my console log doesn't update state but in react debugger tool I do see it's updated.
}

How can use a useEffect so that it always updates state? PS - data is not a local state, it's confined to a certain block.

State updates are asynchronous and will not reflect immediately. Only in next cycle. That is why you can check in useEffect:

useEffect(() => {
console.log(listItem);
},[listItem]);

State is updating correctly.

Not related to the question but, if you are adding to array you might want to do this:

const handleAddProduct = (data) => {
setListItem ([...listItem, data]);
}

Due to Reactjs's update batching , you could not see your updated state within your event handler right after you updated it

If you want to see your value change, place it before the return function of your component:

Something like this:

const handleAddProduct = (data) => {
    setListItem ([...listItem], data)
}

console.log('ListItems-', listItem);

return (
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM