-1
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.

  • 2
    Duplicate of [Why does calling react setState method not mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-does-calling-react-setstate-method-not-mutate-the-state-immediately) – Guy Incognito May 03 '23 at 04:47
  • React is meant to be used asynchronously, so trying to add a delay is not the way to go 99% of the times. Read [this](https://react.dev/reference/react/useState#ive-updated-the-state-but-logging-gives-me-the-old-value) for more. – George Chond May 03 '23 at 05:46

3 Answers3

-1

You can use the useEffect Hooks to get updated state after update state value. and also remove list console log from addItems function.

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


setList((old) => {
  console.log([...old,item]);
  return [...old,item]
});
-1

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.

  
  const delay = (ms) => new Promise(res => setTimeout(res, ms));
  
  const addItems = async () =>{
    setList((old) => {
      return [...old,item]
    });
    setItems('');
    await delay(1000)
    console.log(list);
  }

Recommended solution is use the useEffect hook to reflect any state changes

useEffect(() => {
    console.log(list)
}, [list])
Thusithz
  • 736
  • 1
  • 12
  • 33
-1

changes in state will only be visible in next render(). if you want immediate changes, you can use useRef(); . useRef is smililar to useState but is does not trigger rerender and changes immediately.

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 = () =>{
    let updatedList = [...list, item];
    setList(updatedList);
    setItems('');
    console.log(updatedList);
  }
  return (
    <div>
      <h1>todo</h1>
      <input onChange={(e) => handleChange(e)} value={item} />
      <button onClick={() => addItems()}>Add</button>
    </div>
  )
}

export default App
Jamshaid Tariq
  • 551
  • 1
  • 8
  • 31