Skip to content

Commit d3de20d

Browse files
committed
Add constructor interview questions
1 parent 336fe88 commit d3de20d

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

README.md

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,8 @@
253253
|237| [What is the benefit of component stack trace from error boundary?](#what-is-the-benefit-of-component-stack-trace-from-error-boundary)|
254254
|238| [What is the required method to be defined for a class component?](#what-is-the-required-method-to-be-defined-for-a-class-component)|
255255
|239| [What are the possible return types of render method?](#what-are-the-possible-return-types-of-render-method)|
256+
|240| [What is the main purpose of constructor?](#what-is-the-main-purpose-of-constructor)|
257+
|241| [Is it mandatory to define constructor for React component?](#is-it-mandatory-to-define-constructor-for-react-component)|
256258

257259
## Core React
258260

@@ -4044,4 +4046,20 @@
40444046
2. **Arrays and fragments:** Return multiple elements to render as Arrays and Fragments to wrap multiple elements
40454047
3. **Portals:** Render children into a different DOM subtree.
40464048
4. **String and numbers:** Render both Strings and Numbers as text nodes in the DOM
4047-
5. **Booleans or null:** Doesn't render anything but these types are used to conditionally render content.
4049+
5. **Booleans or null:** Doesn't render anything but these types are used to conditionally render content.
4050+
4051+
240. ### What is the main purpose of constructor?
4052+
The constructor is mainly used for two purposes,
4053+
1. To initialize local state by assigning object to this.state
4054+
2. For binding event handler methods to the instatnce
4055+
For example, the below code covers both the above casess,
4056+
```javascript
4057+
constructor(props) {
4058+
super(props);
4059+
// Don't call this.setState() here!
4060+
this.state = { counter: 0 };
4061+
this.handleClick = this.handleClick.bind(this);
4062+
}
4063+
```
4064+
241. ### Is it mandatory to define constructor for React component?
4065+
No, it is not mandatory. i.e, If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

0 commit comments

Comments
 (0)