skip to Main Content
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


  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]
    });
    Login or Signup to reply.
  2. 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])
    Login or Signup to reply.
  3. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search