useState doesn't update component
See original GitHub issueHere is my code. Clicking the buttons never updates the component. It does change the variable page
but the component itself never re renders or shows the current value of the variable.
react and react-dom are version 16.8.1 babel-core is 6.26.0
const AssessmentWizard = (props) => {
let [page, setPage] = useState(1)
return (
<div>
{page}
<Button onClick={() => setPage(page--)}>Previous Page</Button>
<Button onClick={() => setPage(page++)}>Next Page</Button>
</div>
)
}
additionally, adding the example counter from the intro to hooks doc also didn’t work. I could tell I was clicking a button, but it never changed the view.
Issue Analytics
- State:
- Created 5 years ago
- Comments:14 (5 by maintainers)
Top Results From Across the Web
The useState set method is not reflecting a change immediately
Component or React.PureComponent , the state update using the updater provided by useState hook is also asynchronous, and will not be reflected immediately....
Read more >Why React setState/useState does not update immediately
The answer: They're just queues. React this.setState , and useState does not make changes directly to the state object. React this.setState ...
Read more >Steps to Solve Changes Not Reflecting When useState Set ...
The “useState” set method is asynchronous; hence, the updates are not reflected immediately. However, this is not the reason for the change not ......
Read more >React useState set method does not reflect the change ...
The reason for React state updates not being reflected immediately is due to the current closure of the state variable. It is still...
Read more >Why React doesn't update state immediately - LogRocket Blog
When developing React applications, you may have noticed that state updates don't immediately reflect new values after being changed.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
page++
insidesetPage
means “after setting state, increase page by 1”. The fix is to use++page
because it’d increase page by1
and then set state.In your case, you should be using neither of them as
state
should only be mutated bysetPage
. For example, when doingpage--
or--page
, under the hood, they’re actuallypage = page - 1
.I will also lock because issues like this tend to attract misinformation and wrong workarounds. Again — if you can reproduce this reliably and don’t use experimental projects like
react-hot-loader
then please file a new issue with a reproducing case. Thanks.