Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UseState shows previous value always [duplicate]

This is a popular question among all the new react developers but somehow I'm not able to understand the logic behind available solutions. I'm trying to update the state variable using hooks and trying it read the updated value but always it returns a previous value instead of new value. Below is the sequence of my code execution.

onClick={setTransactionAccountId}

on button click, it executes the below code and updates the state but the console.log shows the old value.

const [accountId, setAccountId] = useState(0);

const setTransactionAccountId = e => {
  console.log("Clicked ID:", e.currentTarget.value);
  setAccountId(e.currentTarget.value);
  console.log("accountId:", accountId);
};

console log:

  1. first button click:

Clicked ID: 0 accountId: 0

  1. second button click:

Clicked ID: 1 accountId: 0

could anyone please tell me the reason behind this behaviour and how to tackle it.

like image 596
vivek.p.n manu Avatar asked Feb 27 '20 17:02

vivek.p.n manu


People also ask

Is useState synchronous or asynchronous?

TL;DR: useState is an asynchronous hook and it doesn't change the state immediately, it has to wait for the component to re-render. useRef is a synchronous hook that updates the state immediately and persists its value through the component's lifecycle, but it doesn't trigger a re-render.

Why we use useRef instead of useState?

If you want to update data and cause a UI update, useState is your Hook. If you need some kind of data container throughout the component's lifecycle without causing render cycles on mutating your variable, then useRef is your solution.


1 Answers

accountId won't have been updated this render. You have to wait for the next render for it to be updated. accountId only gets populated at the top of the function component when useState is called. You're in the middle of the render. If you need the actual value, keep pulling it out of e.currentTarget.value.

like image 163
zero298 Avatar answered Sep 17 '22 00:09

zero298