Buy @ Amazon

3 Ways To Initialize State In React


First things first, this blog post is an extension of the demo project that showcases the 3 ways to initialize state in React Component. This project source code is open-sourced in Github (karthiks/simple-counter-react-demo) for your reference and toying with it.

The 3 ways are:
  1. Class Component that uses constructor to initialise state.
  2. Class Component that uses static/class property to initialise state.
  3. Functional Component (aka Function) that uses React Hook viz. useState to initialise state.
The evolution has been in that order as shown above. With the advent of ES6, react leveraged constructor to initialise component state. This one unified the practices by various teams. However this method has a constraint that the constructor's first statement should be "super(props);", failing which things might not work as expected. To err is human and developers missed this line occassionaly resulting in painful debugging.

But a developer is smart. With the advent of ESLint this issue was resolved. That said, Babel users start to leverage static/class property feature available in Babel, for it is concise and looks cleaner. Note this class property isn't a feature of Javascript as yet and so would result in constructor being generated for you by Babel.

In the mean time, React introduced easier way to define stateless components with just functions. These are called Stateless / Functional Components. And with time React also introduced React Hooks. One of the hooks were useState that hooks state into a component. With the advent of this, the community started to leverage this one over the above methods.

Your mileage and preference may vary. This project is aimed to help you decide the flavor you prefer and start adopting.