You can keep the list unchanged and use another state to update the ui:

const [list, setList] = useState(list);
const [count, setCount] = useState(list.length);

useEffect(() => {
}, [newItem, list]);


The general approach of using the setter's callback instead of having to refer to the outer state value is perfectly normal and acceptable. You can slim it down too:

useEffect(() => {
  setList(prevList => [...prevList, newItem]);
}, [newItem]);

But it's a little bit strange to have a separate newItem state that immediately gets merged into the list. Consider if you could merge them together so you only have one stateful variable in the end. Instead of doing



setList(prevList => [...prevList, theNewItem]);

and then, wherever else you refer to newItem, change it to list[list.length - 1] - or do

const newItem = list[list.length - 1];

in the body of the component.

That approach won't work for all situations, but consider whether it'd be applicable to yours.

Related Query

More Query from same tag