React Initial State Example
Learning React it is very important to understand what state is, the concept and really how does it work. Let’s take a stab at understanding what state is and how it works. Check out this post about React JS Initial State…
What is State?
Each component has its state, and we can define its initial state.
States is only available to components that are called class components.
Let’s check it in an examples below…
Don’t miss out
if an event occurs on the web page or we receive the data from the AJAX request then we must reset the component state and update the data of the component. Instead, we can also define the Initial State for the particular component.
Firstly, let’s create our playground 🏈
npm install -g create-react-app
It will open a browser, and at port 3000
You don’t need to refresh the page if you perform a change as it will simulate automatically, and you can see the updated view.
Let’s Define Initial state
Locate & open the app.js file
Here, I have defined the Initial State of the component class.
If we want to change the state after clicking the button and get the AJAX request response, then we just write following line to change the state.
Example 2 — Constructor
According to the official documentation, the constructor is the right place to initialize state.
Therefore we define the initial state of the component on the following constructor method.
Just keep in mind :)
- Do not write setState() in the constructor. It will not work.
- You do not need to change the state directly except for the initial state
- we always need to use the setState method to change the state.
You will be handling state very often while developing React application.
I recommend React’s official documentation on State and Lifecycle
That’s it for now.
If you liked this article, then please subscribe to my YouTube Channel for video tutorials.
Originally published at Panayiotis Georgiou.