Member-only story
React Basics — What goes in constructor?
Jan 7, 2022
When is the constructor called?
The constructor for a React component is called before it is mounted.
What goes in the constructor?
- Here you may call super(props) if you are implementing the constructor for a React.Component subclass.
- Here you may initialize local state by assigning an object to
this.state
- Here you may bind event handler methods to an instance.
- 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.state
directly.
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.