This article explains one of the most common pitfalls in React — why a component’s state doesn’t update immediatelyafter calling setState (or useState in functional components). Using a simple “Subscribe” form example, it demonstrates how asynchronous state updates work and how to properly manage input-driven UI behavior.
In the React environment, working with properties and states is an obvious thing, because both props and state represent rendered values, i.e., what’s currently seen on the screen.
To apply changes to a component we need to change the components state or props. React only updates what’s necessary by comparing an element and its children to the previous one, and applies the DOM updates to bring the DOM to the desired state.
Like React documentation suggests:
Once you create an element, you can’t change its children or attributes. An element is like a single frame in a movie: it represents the UI at a certain point in time.
What is going on here?We have a stateful Subscribe Component with two simple events:
handleSubmit — sets the input value from the input field and displays it on UI
handleChange — reads text from the input field and stores it in inputValue and in the same place sets the submitValue which is incorrect and will cause a problem reflected on UI.
Under our simple form, we have two sections with live date from input field. The first one shows what user types in the input field. The second one indicates what will be sent from our form.Right now our code is broken.
Right now our code is broken.
Once we start writing, you can see that inputValue is different than submitValue. That is exactly our case! We are setting state before it was changed. To fix that we need to:
set our submitValue in handleChange function to be equal to the currentValue
Without that, even if we deleted all characters from the input field our state will be behind. In addition, our submit method does nothing else than login ’Subscribed’ in the browser console and setting state for submitValue.