import React,{ useState,useEffect } from 'react'
import './App.css'
const App = () => {
const [item, setItems] = useState('');
const [list, setList] = useState([]);
const handleChange = (e) =>{
setItems(e.target.value)
}
const addItems = () =>{
setList((old) => {
return [...old,item]
});
setItems('');
console.log(list);
}
return (
<div>
<h1>todo</h1>
<input onChange={(e) => handleChange(e)} value={item} />
<button onClick={() => addItems()}>Add</button>
</div>
)
}
export default App
This is a todo list app. What can i do to update the addItems() function immediately.whenever i call the addItems() the older value comes back.
3
Answers
You can use the useEffect Hooks to get updated state after update state value. and also remove list console log from addItems function.
Even if you add delay that updates will not reflect immediately. The below example introduces a descent time delay for useState to complete the asynchronous operation. Still we see the old state value. Because the state variable still belongs to the old closure.
Recommended solution is use the useEffect hook to reflect any state changes
changes in state will only be visible in next
render()
. if you want immediate changes, you can useuseRef();
.useRef
is smililar to useState but is does not trigger rerender and changes immediately.