As frontend developers we keep hearing about state, and it can be confusing to begin with. When I started out I had no clue that such a thing existed. It took me sometime to figure out this state thing. In this post, let’s try and understand what is state.
So what is state?
State is the data that represents the current state of your UI. Key thing to note is that it is the data not the actual UI(DOM). This data is then used to render the UI correctly.
Examples
Let’s take a look at couple of examples:
Network call :
The App will go through these states:
isLoading
(is the network call in progress)isSuccess
(is the network call a success)isError
(if the call returned an error)
Now depending on any of these states our UI will change, as an example
- if
isLoading
istrue
we show the loading animation - if
isSuccess
istrue
we hide the loading animation and show the response - if
isError
istrue
we hide the loading animation and show the error message
Form submission :
isValid
(is the form valid/all the fields are filled in correctly)isSubmitted
(is the form submitted)
When the user clicks on submit
- If
isValid
istrue
we submit the form else show an error - If
isSubmitted
is true we hide the form and show a message that form is submitted (This is just an example, in the real world you might submit the form by making a network call or each field can have it’s own state to check if it’s valid and capture the value.)
When does the state update?
- Every action that the user performs in your app, will update the state and this in turn will update the UI.
Examples of user actions:
- route change
- focus on a input field
- submit a form
- Side effects after the initial state change, like network call after route change.
- Push notification, to show the user that there is a new notification or update.
That’s all for today, next time we have a look at state management.
Cover photo by Nathan Dumlao on Unsplash