Member-only story

React Basics — What goes in constructor?

Marika Lam
Jan 7, 2022

--

Photo by Cia Gould on Unsplash

When is the constructor called?

The constructor for a React component is called before it is mounted.

What goes in the constructor?

  1. Here you may call super(props) if you are implementing the constructor for a React.Component subclass.
  2. Here you may initialize local state by assigning an object to this.state
  3. Here you may bind event handler methods to an instance.
  4. You don’t need to implement a constructor if none of the above 3 reasons apply to your class.

Warning: You should not call setState() in the constructor. Instead, assign the initial state to this.statedirectly.

Summary

The constructor is a method that’s automatically called during the creation of an object from a class. Simply put, the constructor aids in constructing things.

References

https://reactjs.org/docs/react-component.html#constructor

--

--

No responses yet