profile
viewpoint

Ask questionsStale values for useState inside callback functions

<!-- Note: if the issue is about documentation or the website, please file it at: https://github.com/reactjs/reactjs.org/issues/new -->

Do you want to request a feature or report a bug? potential bug

What is the current behavior? When calling setState from useState, the state value is stale from inside a function. The value is correct inside the body of the component, but not inside the function itself.

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below: Begin by typing a@g which should autocomplete to a@gmail.com. You will see the expected and actual values for the input below each. https://codesandbox.io/s/useemailautocomplete-material-ui-04423

What is the expected behavior? It should have the correct value for email inside the handleChange function.

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React? React: v16.12.0 Browser: chrome OS: Catalina

facebook/react

Answer questions aweary

I feel like that behavior is not very desirable. In the past, in most cases, when state was updated it was reflected on the next line within a function.

This behavior has been around since before Hooks and is important for a few reasons. Check out the official FAQ, which covers this question. Hopefully that clears things up!

useful!

Related questions

Disable react strict mode on third party libraries hot 4
Refs - &#34;object is not extensible&#34; hot 4
Warning: Unknown DOM property for. Did you mean htmlFor? hot 4
Warning: validateDOMNesting(...): <tr> cannot appear as a child of <table> hot 3
React@16.9 block `javascript:void(0);` hot 3
DevTools: Updating state or props in devtools does not trigger component update. hot 2
Hooks API - hook breaks when exported from module hot 2
Feedback on useEffect depndencies change error hot 2
React custom hook "Should have a queue. This is likely a bug in React" error message. hot 1
TypeError: Object(...) is not a function hot 1
useEffect causes 'callback is not a function' exception hot 1
Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component hot 1
eslint-plugin-react-hooks v2.0.0 is not loaded correctly. hot 1
Old references retained by memoizedProps in fiber hot 1
ReactDomServer - renderToString Failing with Context Provider on IE11 hot 1
Github User Rank List