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.

Answer from zero298 on Stack Overflow
๐ŸŒ
React
react.dev โ€บ reference โ€บ react โ€บ useState
useState โ€“ React
The set function that lets you update the state to a different value and trigger a re-render. useState is a Hook, so you can only call it at the top level of your component or your own Hooks. You canโ€™t call it inside loops or conditions.
๐ŸŒ
Medium
abidemi-dev.medium.com โ€บ react-hooks-usestate-with-previous-state-55b6272f1473
React Hooks: useState with previous state | by Abidemi Animashaun | Medium
August 10, 2021 - So setCount accepts a function that has access to the old count. So prevCount is the argument and the function body prevCount + 1. We pass in a function that has access to the old value and increment that by one. Anytime you need to update the state value based on the previous state value, always go with the safer option of passing in a function that will set the new state value.
Discussions

reactjs - React useState update based on a variables previous value - Stack Overflow
Does this answer your question? Updating and merging state object using React useState() hook. ~ * ~ This fine answer shows an example of when not using a function leads to the wrong behavior. ... count is never updated based on its previous value. it gets updated based on its current value. More on stackoverflow.com
๐ŸŒ stackoverflow.com
reactjs - state (from useState) using old value on a callback - Stack Overflow
We use this when our new state is derived from old state. Only this syntax would have the "freshest" value of the old state 2021-07-02T17:29:27.323Z+00:00 More on stackoverflow.com
๐ŸŒ stackoverflow.com
July 1, 2021
console log showing previous number used on useState
Is your console log within the function that calls the setState or in render? State updates are async, so the new state value wonโ€™t be instantly available in the next line of that function, but I imagine if your console log were in render you would see the updated value on the next render cycle once the state update is processed. More on reddit.com
๐ŸŒ r/reactjs
4
4
July 30, 2022
How does Javascript/React know to pass in the previous value of a stateful variable?
React keeps the actual current props and state for each component in internal data structures called "Fibers". That's how it knows what components currently exist in the component tree, and how to update them. In this case, when you pass an updater function into setState, React will eventually call const newState = updaterFunction(fiber.prevState). See my extensive post A (Mostly) Complete Guide to React Rendering Behavior to better understand how this actually works. More on reddit.com
๐ŸŒ r/reactjs
15
0
June 9, 2024
People also ask

How to Update State Based on Previous State?
To update the state based on the previous state in React, use the functional update form of the setter function provided by useState. This guarantees that you're working with the most recent state value.
๐ŸŒ
dhiwise.com
dhiwise.com โ€บ post โ€บ best-practices-for-preservingprevious-state-in-react-usestate
Mastering React's useState: Handling Previous State
The Role of useEffect in Tracking State Changes
The useEffect hook can be used with useState to perform side effects in response to state changes. It can also be used to track previous state values by using refs.
๐ŸŒ
dhiwise.com
dhiwise.com โ€บ post โ€บ best-practices-for-preservingprevious-state-in-react-usestate
Mastering React's useState: Handling Previous State
๐ŸŒ
LogRocket
blog.logrocket.com โ€บ home โ€บ how to access previous props or state with react hooks
How to access previous props or state with React Hooks - LogRocket Blog
June 4, 2024 - Indeed, useState allows us to access the previous state. ... In this example, count is our previous state and we are deciding how to transform it before setting it to the current count.
๐ŸŒ
DEV Community
dev.to โ€บ vvkkumar06 โ€บ create-a-modified-usestate-hook-to-get-previous-value-53mk
Create a modified useState hook to get previous value - DEV Community
December 27, 2023 - Create a state using useState, take initialState as parameter in our custom hook and return state and setState.
Find elsewhere
๐ŸŒ
Greenroots
blog.greenroots.info โ€บ react-hook-usestate-lazy-initialization-previous-state
ReactJS useState Hook - lazy initialization and previous state
February 17, 2022 - Please find the updated source code with lazy initialization and previous state value usages from here: The Source Code on Stackblitz ยท To conclude, ReactJS's standard hooks got lots to offer when you use functional components. The useState hook helps us create and track the state changes.
๐ŸŒ
useHooks
usehooks.com โ€บ useprevious
usePrevious React Hook โ€“ useHooks
November 7, 2018 - The usePrevious hook is a useful tool for tracking the previous value of a variable in a functional component.
๐ŸŒ
DhiWise
dhiwise.com โ€บ post โ€บ best-practices-for-preservingprevious-state-in-react-usestate
Mastering React's useState: Handling Previous State
August 5, 2024 - When a state variable is updated, React re-renders the component to reflect the new state. The term "previous state" refers to the state value of a component before the most recent update.
๐ŸŒ
Telerik
telerik.com โ€บ blogs โ€บ how-to-access-previous-props-state-values-react-hooks
How to Access Previous Props & State Values with React Hooks
February 26, 2024 - To use refs to store the previous values of states, we can assign those values to refs. For instance, we write: import { useRef, useState } from "react"; export default function App() { const prevCountRef = useRef(); const [count, setCount] ...
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ how does javascript/react know to pass in the previous value of a stateful variable?
r/reactjs on Reddit: How does Javascript/React know to pass in the previous value of a stateful variable?
June 9, 2024 -

When studying react and first learning the useState hook, I came across a scenario where I had to update state based on the previous value of the stateful variable.

The original code was:

const [state, setState] = useState('')

and the code in the event handler function was:

setState(prev => prev + 1)

My main question is in situations in Javascript like this where we pass a variable/parameter into a function, how does the computer know that 'prev' is the previous value of the stateful variable? There are a lot of situations like this where I am passing a variable into a function but I dont understand how the computer knows the exact variable I want to pass so I'd like to know how to tell exactly what is passed into a function. Thanks in advance.

Top answer
1 of 5
30
React keeps the actual current props and state for each component in internal data structures called "Fibers". That's how it knows what components currently exist in the component tree, and how to update them. In this case, when you pass an updater function into setState, React will eventually call const newState = updaterFunction(fiber.prevState). See my extensive post A (Mostly) Complete Guide to React Rendering Behavior to better understand how this actually works.
2 of 5
6
Try writing it yourself! Here is an example I quickly wrote: const setState = (originalValue) => { const hookValue = originalValue; const setter = (newValue) => { if(typeof newValue === 'function') { hookValue = newValue(hookValue) } else { hookValue = newValue } } return [hookValue, setter] } I feel like its easier if I wrote this in typescript but in general I hope you get the idea. When you pass the setter a function it calls that function with the hook value. So your function gets the state value as the parameter and then calls that function and sets its return value. Its one of those things that feels really complex but once you've gotten used to the idea of passing functions in as arguments and composing functions with functions it gets second nature and most problems can just be easily solved with some creative composition. Obviously this is a very simple example and react under the hood does a lot more things when the setter is called to 'hook into' react but in general the idea is the same: If its a function it'll call with the latest value and set the return of that function to state. If its not a function it'll set that value to state.
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ reactjs usestate behavior on updating the state with new value and then with the previous value in the same function.
r/reactjs on Reddit: ReactJs useState behavior on updating the state with new value and then with the previous value in the same function.
June 29, 2024 -

I am little confused how react state works in react functional components.

In the below code i am trying to update the count state with new value and then with the previous value in the same function when i click on the button.
And i observe that my function is rerendered in this case and and with this i am updating my temp variable with a random number. But i didn't see the change in the value of temp in the DOM regardless the temp value is changing .

import React, { useEffect, useState } from 'react'

let temp;
function App() {
  console.log("rendering")
  const [count, setCount] = useState(0)

  temp=Math.random(0,1);
  console.log("temp value is :",temp)

  function handleCount(){
    setCount(1)
    setCount(0)
  }

  return (
    <div>
      <h2>Count value is:{count}</h2>
      <button onClick={handleCount}>Click me</button>
      <p>temp value is :{temp}</p>
    </div>
  )
}

export default App

Output in console:-

Initial Render: Rendering temp value is : 0.309

1st button click: Rendering temp value is : 0.257

2nd button click: Rendering temp value is : 0.951

Output in UI is same in each button click:-

Count value is: 0

temp value is : 0.309

My question is simple that why my temp value is not changing in the dom regardless my component is rerenderd in every button click .

Can anyone tell me how useState works and specially for the above code.

๐ŸŒ
React
legacy.reactjs.org โ€บ docs โ€บ hooks-reference.html
Hooks API Reference โ€“ React
During subsequent re-renders, the first value returned by useState will always be the most recent state after applying updates.
๐ŸŒ
BOSC Tech Labs
bosctechlabs.com โ€บ home โ€บ blog โ€บ how to solve changes not reflecting when usestate set method applied?
Steps to Solve Changes Not Reflecting When useState Set Method Applied
August 1, 2024 - When the โ€œuseStateโ€ set method is not reflecting a change immediately, it may be due to the current closure of the state variable. Hence, it is still referring to the old value of the state.