etc. This function returns the same result each time it is invoked. Example: If you need to display a heading, you can do this as below.
Points to Note:
- Each render() function contains a return statement.
- The return statement can have only one parent HTML tag.
15) How can you embed two or more components into one?
You can embed two or more components into the following way:
16) What is Props?
Props stand for "Properties" in React. They are read-only inputs to components. Props are an object which stores the value of attributes of a tag and work similar to the HTML attributes. It gives a way to pass data from the parent to the child components throughout the application.
It is similar to function arguments and passed to the component in the same way as arguments passed in a function.
Props are immutable so we cannot modify the props from inside the component. Inside the components, we can add attributes called props. These attributes are available in the component as this.props and can be used to render dynamic data in our render method.
For More Information, Click here.
17) What is a State in React?
The State is an updatable structure which holds the data and information about the component. It may be changed over the lifetime of the component in response to user action or system event. It is the heart of the react component which determines the behavior of the component and how it will render. It must be kept as simple as possible.
Let's create a "User" component with "message state."
For More Information, Click here.
18) Differentiate between States and Props.
The major differences between States and Props are given below.
SN |
Props |
State |
1. |
Props are read-only. |
State changes can be asynchronous. |
2. |
Props are immutable. |
State is mutable. |
3. |
Props allow you to pass data from one component to other components as an argument. |
State holds information about the components. |
4. |
Props can be accessed by the child component. |
State cannot be accessed by child components. |
5. |
Props are used to communicate between components. |
States can be used for rendering dynamic changes with the component. |
6. |
The stateless component can have Props. |
The stateless components cannot have State. |
7. |
Props make components reusable. |
The State cannot make components reusable. |
8. |
Props are external and controlled by whatever renders the component. |
The State is internal and controlled by the component itself. |
For More Information, Click here.
19) How can you update the State of a component?
We can update the State of a component using this.setState() method. This method does not always replace the State immediately. Instead, it only adds changes to the original State. It is a primary method which is used to update the user interface(UI) in response to event handlers and server responses.
Example
For More Information, Click here.
20) Differentiate between stateless and stateful components.
The difference between stateless and stateful components are:
SN |
Stateless Component |
Stateful Component |
1. |
The stateless components do not hold or manage state. |
The stateful components can hold or manage state. |
2. |
It does not contain the knowledge of past, current, and possible future state changes. |
It can contain the knowledge of past, current, and possible future changes in state. |
3. |
It is also known as a functional component. |
It is also known as a class component. |
4. |
It is simple and easy to understand. |
It is complex as compared to the stateless component. |
5. |
It does not work with any lifecycle method of React. |
It can work with all lifecycle method of React. |
6. |
The stateless components cannot be reused. |
The stateful components can be reused. |
21) What is arrow function in React? How is it used?
The Arrow function is the new feature of the ES6 standard. If you need to use arrow functions, it is not necessary to bind any event to 'this.' Here, the scope of 'this' is global and not limited to any calling function. So If you are using Arrow Function, there is no need to bind 'this' inside the constructor. It is also called 'fat arrow '(=>) functions.
22) What is an event in React?
An event is an action which triggers as a result of the user action or system generated event like a mouse click, loading of a web page, pressing a key, window resizes, etc. In React, the event handling system is very similar to handling events in DOM elements. The React event handling system is known as Synthetic Event, which is a cross-browser wrapper of the browser's native event.
Handling events with React have some syntactical differences, which are:
- React events are named as camelCase instead of lowercase.
- With JSX, a function is passed as the event handler instead of a string.
For More Information, Click here.
23) How do you create an event in React?
We can create an event as follows.
Example
For More Information, Click here.
24) What are synthetic events in React?
A synthetic event is an object which acts as a cross-browser wrapper around the browser's native event. It combines the behavior of different browser's native event into one API, including stopPropagation() and preventDefault().
In the given example, e is a Synthetic event.
25) what is the difference between controlled and uncontrolled components?
The difference between controlled and uncontrolled components are:
SN |
Controlled |
Uncontrolled |
1. |
It does not maintain its internal state. |
It maintains its internal states. |
2. |
Here, data is controlled by the parent component. |
Here, data is controlled by the DOM itself. |
3. |
It accepts its current value as a prop. |
It uses a ref for their current values. |
4. |
It allows validation control. |
It does not allow validation control. |
5. |
It has better control over the form elements and data. |
It has limited control over the form elements and data. |
For More Information, Click here.
26) Explain the Lists in React.
Lists are used to display data in an ordered format. In React, Lists can be created in a similar way as we create it in JavaScript. We can traverse the elements of the list using the map() function.
Example
For More Information, Click here.
27) What is the significance of keys in React?
A key is a unique identifier. In React, it is used to identify which items have changed, updated, or deleted from the Lists. It is useful when we dynamically created components or when the users alter the lists. It also helps to determine which components in a collection needs to be re-rendered instead of re-rendering the entire set of components every time. It increases application performance.
For More Information, Click here.
28) How are forms created in React?
Forms allow the users to interact with the application as well as gather information from the users. Forms can perform many tasks such as user authentication, adding user, searching, filtering, etc. A form can contain text fields, buttons, checkbox, radio button, etc.
React offers a stateful, reactive approach to build a form. The forms in React are similar to HTML forms. But in React, the state property of the component is only updated via setState(), and a JavaScript function handles their submission. This function has full access to the data which is entered by the user into a form.
For More Information, Click here.
29) What are the different phases of React component's lifecycle?
The different phases of React component's lifecycle are:
Initial Phase: It is the birth phase of the React lifecycle when the component starts its journey on a way to the DOM. In this phase, a component contains the default Props and initial State. These default properties are done in the constructor of a component.
Mounting Phase: In this phase, the instance of a component is created and added into the DOM.
Updating Phase: It is the next phase of the React lifecycle. In this phase, we get new Props and change State. This phase can potentially update and re-render only when a prop or state change occurs. The main aim of this phase is to ensure that the component is displaying the latest version of itself. This phase repeats again and again.
Unmounting Phase: It is the final phase of the React lifecycle, where the component instance is destroyed and unmounted(removed) from the DOM.
For More Information, Click here.
30) Explain the lifecycle methods of React components in detail.
The important React lifecycle methods are:
- getInitialState(): It is used to specify the default value of this.state. It is executed before the creation of the component.
- componentWillMount(): It is executed before a component gets rendered into the DOM.
- componentDidMount(): It is executed when the component gets rendered and placed on the DOM. Now, you can do any DOM querying operations.
- componentWillReceiveProps(): It is invoked when a component receives new props from the parent class and before another render is called. If you want to update the State in response to prop changes, you should compare this.props and nextProps to perform State transition by using this.setState() method.
- shouldComponentUpdate(): It is invoked when a component decides any changes/updation to the DOM and returns true or false value based on certain conditions. If this method returns true, the component will update. Otherwise, the component will skip the updating.
- componentWillUpdate(): It is invoked before rendering takes place in the DOM. Here, you can't change the component State by invoking this.setState() method. It will not be called, if shouldComponentUpdate() returns false.
- componentDidUpdate(): It is invoked immediately after rendering takes place. In this method, you can put any code inside this which you want to execute once the updating occurs.
- componentWillUnmount(): It is invoked immediately before a component is destroyed and unmounted permanently. It is used to clear up the memory spaces such as invalidating timers, event listener, canceling network requests, or cleaning up DOM elements. If a component instance is unmounted, you cannot mount it again.
For More Information, Click here.
31) What are Pure Components?
Pure components introduced in React 15.3 version. The React.Component and React.PureComponent differ in the shouldComponentUpdate() React lifecycle method. This method decides the re-rendering of the component by returning a boolean value (true or false). In React.Component, shouldComponentUpdate() method returns true by default. But in React.PureComponent, it compares the changes in state or props to re-render the component. The pure component enhances the simplicity of the code and performance of the application.
32) What are Higher Order Components(HOC)?
In React, Higher Order Component is an advanced technique for reusing component logic. It is a function that takes a component and returns a new component. In other words, it is a function which accepts another function as an argument. According to the official website, it is not the feature(part) in React API, but a pattern that emerges from React's compositional nature.
For More Information, Click here.
33) What can you do with HOC?
You can do many tasks with HOC, some of them are given below:
- Code Reusability
- Props manipulation
- State manipulation
- Render highjacking
34) What is the difference between Element and Component?
The main differences between Elements and Components are:
SN |
Element |
Component |
1. |
An element is a plain JavaScript object which describes the component state and DOM node, and its desired properties. |
A component is the core building block of React application. It is a class or function which accepts an input and returns a React element. |
2. |
It only holds information about the component type, its properties, and any child elements inside it. |
It can contain state and props and has access to the React lifecycle methods. |
3. |
It is immutable. |
It is mutable. |
4. |
We cannot apply any methods on elements. |
We can apply methods on components. |
5. |
Example: const element = React.createElement( 'div', {id: 'login-btn'}, 'Login' ) |
Example: function Button ({ onLogin }) { return React.createElement( 'div', {id: 'login-btn', onClick: onLogin}, 'Login' ) } |
35) How to write comments in React?
In React, we can write comments as we write comments in JavaScript. It can be in two ways:
1. Single Line Comments: We can write comments as /* Block Comments */ with curly braces:
2. Multiline Comments: If we want to comment more that one line, we can do this as
36) Why is it necessary to start component names with a capital letter?
In React, it is necessary to start component names with a capital letter. If we start the component name with lower case, it will throw an error as an unrecognized tag. It is because, in JSX, lower case tag names are considered as HTML tags.
37) What are fragments?
In was introduced in React 16.2 version. In React, Fragments are used for components to return multiple elements. It allows you to group a list of multiple children without adding an extra node to the DOM.
Example
There is also a shorthand syntax exists for declaring Fragments, but it's not supported in many tools:
For More Information, Click here.
38) Why are fragments better than container divs?
39) How to apply validation on props in React?
Props validation is a tool which helps the developers to avoid future bugs and problems. It makes your code more readable. React components used special property PropTypes that help you to catch bugs by validating data types of values passed through props, although it is not necessary to define components with propTypes.
We can apply validation on props using App.propTypes in React component. When some of the props are passed with an invalid type, you will get the warnings on JavaScript console. After specifying the validation patterns, you need to set the App.defaultProps.
For More Information, Click here.
40) What is create-react-app?
Create React App is a tool introduced by Facebook to build React applications. It provides you to create single-page React applications. The create-react-app are preconfigured, which saves you from time-consuming setup and configuration like Webpack or Babel. You need to run a single command to start the React project, which is given below.
This command includes everything which we need to build a React app. Some of them are given below:
- It includes React, JSX, ES6, and Flow syntax support.
- It includes Autoprefixed CSS, so you don't need -webkit- or other prefixes.
- It includes a fast, interactive unit test runner with built-in support for coverage reporting.
- It includes a live development server that warns about common mistakes.
- It includes a build script to bundle JS, CSS, and images for production, with hashes and source maps.
For More Information, Click here.
React Refs Interview Questions
41) What do you understand by refs in React?
Refs is the shorthand used for references in React. It is an attribute which helps to store a reference to particular DOM nodes or React elements. It provides a way to access React DOM nodes or React elements and how to interact with it. It is used when we want to change the value of a child component, without making the use of props.
For More Information, Click here.
42) How to create refs?
Refs can be created by using React.createRef() and attached to React elements via the ref attribute. It is commonly assigned to an instance property when a component is created, and then can be referenced throughout the component.
43) What are Forward Refs?
Ref forwarding is a feature which is used for passing a ref through a component to one of its child components. It can be performed by making use of the React.forwardRef() method. It is particularly useful with higher-order components and specially used in reusable component libraries.
Example
For More Information, Click here.
44) Which is the preferred option callback refs or findDOMNode()?
The preferred option is to use callback refs over findDOMNode() API. Because callback refs give better control when the refs are set and unset whereas findDOMNode() prevents certain improvements in React in the future.
The recommended approach is: