Search code examples
reactjsuse-effectuse-state

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 i.e.

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? P.S. - data is not a local state, it's confined to a certain block.


Solution

  • 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 (
    );