Different ways to Initialize State in React

Jeffrey Martinez
3 min readApr 22, 2021

Within this blog we will cover two of the most common ways on how to initialize state within React Class Components! We will discuss what is state, why we need state, and how to initialize! Let’s Get Started!

What is state?

State of a component is an object that holds some information that may change over the lifetime of the component. We should always try to make our state as simple as possible and minimize the number of stateful components.

Why we need state?

When using state, this makes the component more dynamic and enables to keep track of changing information in between renders for it to be dynamic and interactive.

How to initialize state?

There are 2 most common ways we can initialize state.

The first one below is establishing a contructor function and initializing state from within. Take a look below:

Why do we call super(props) ?

Our Greeting component is borrowing functionality from our React.Component Class. This base class has a constructor function of its own. When we define a constuctor function, we are essentially overiding or replacing the constructor method from the React.Component Class. We still want to make sure that all the setup code that is within the constructor of the React.Component can be used within the Greeting Component. We call super(props) as a reference to the parent’s constructor function.

What if I told you there is a second way to initialize state with less code, what would you say? Let’s try it!

Check this out! We are initalizing state without even needing a constructor and without needing to call super.

The second initialization is equivalent to the first initialization, but how do we know that? Babel takes our code and implements the constructor method for us. With Babel, we can simplify our code to the looking like the second initialization. Babel is a JavaScript compiler which converts the current ECMAScript version into a compatible version that every internet browser can use. Take a look below how babel converts our second initialization:

Try it out yourself on Babel! Here you can see on line 6 on the compiled version, the constructor is defined and on line 7 you can see the super being established. By initalializing state without a constructor function, you simplify your code.

Resources

Learn more about initializing state in React Class Compents by clicking here, or view below! Also check out the React documentation!

--

--

Jeffrey Martinez

I am a graduate from Flatiron School for Software Engineer. Studied HTML, CSS, Ruby, Ruby on Rails, JavaScript, React, Redux, Sinatra, and Sqlite3