How do you initialize state in a class component?
In a class component in React, you initialize state in the constructor method.
Javascript
import React from 'react' ; class MyComponent extends React.Component { constructor(props) { super (props); // Initialize state in the constructor this .state = { count: 0, name: 'John' , isLoggedIn: false }; } render() { return ( <div> <h1>Hello, { this .state.name}!</h1> <p>Count: { this .state.count}</p> <p>User is logged in : { this .state.isLoggedIn ? 'Yes' : 'No' }</p> </div> ); } } export default MyComponent; |
Top React Components Interview Questions & Answers
React Component is the building blocks of the React application. It is the core concept that everyone must know while working on React. In this tutorial, we will see the top React Components questions that can be asked in the interview.
Let’s discuss some common questions that you should prepare for the interviews. These questions will be helpful in clearing the interviews, especially for the frontend development or full stack development role.