1
const ExpenseItem = (props) => {

  const [title, setTitle] = useState(props.title);
  const date = props.date;
  const amount = props.amount;

  function clickHandler(){
    setTitle("Updated");
    console.log(title);  
  }

  return (
    <Card className='expense-item'>
      <ExpenseCalender
        month = {date.toLocaleString("default", {month: "long"})}
        day = {date.toLocaleString("default", {day: "2-digit"})}
        year = {date.getFullYear()}
      />
      <div className='expense-item__description'>
          <h2>{title}</h2>
          <div className='expense-item__price'>{`$${amount}`}</div>
      </div>
      <button onClick={clickHandler}>Change title</button>
    </Card>
  )
}

expected that console.log(title) will give output as 'Updated'

But it was rendering the old title i.e the title data from the props.

  • 2
    setTitle() is asynchronous, which means that at the time you console.log the state, it's not updated yet – Kevin Bui Oct 29 '22 at 06:36
  • You should use useEffect() hook – Kevin Bui Oct 29 '22 at 06:38
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – user3840170 Oct 29 '22 at 09:12

1 Answers1

1

As @Kevin Bui said in comment

setTitle() is asynchronous, which means that at the time you console.log the state, it's not updated yet

Which mean In the next line you will not get the updated value. Or other words it doesn't wait for updating the value then go to the next line.

So what is happening here is. If you console.log after the settitle() it will give you old state.

Solution 1:Log outside the function anywhere Usually I keep all my logs before return statement

console.log(title)
return (
.........
)

Solution 2:use useEffect() hook

useEffect(() => {
    // action on update of title
}, [title]);

Solution 3:use simple variable instead of usestate()

const title = props.title;

To know more about problem solution go here

Devam Sanghvi
  • 548
  • 1
  • 5
  • 11