Oh Snap!

Please turnoff your ad blocking mode for viewing your site content

React Initial State Example

/
/
/
0 Views

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?

State, in React, is a plain JavaScript object that allows you keep track of a component’s data.

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

React.js First Attempt

Build iOS App with React Native and Expo

Example 1

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

create-react-app react-initial-state

cd react-initial-state

npm start

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.

Github Example

Follow me on Instagram

Final Thoughts

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.

You can also find me on Twitter and Facebook.

The post React Initial State Example appeared first on Panayiotis Georgiou.

  • Facebook
  • Twitter
  • Google+
  • Linkedin
  • Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.