What is React and What are the features of React?
React is a front-end JavaScript library for building user interfaces. It is an open-source Framework. It is one of the most important JavaScript frameworks that any JS aspirant must know about.it was created by Jordan Walke. It was developed by Facebook in 2011.
Some features of React are:
- Virtual DOM
- UI Focused
- JSX (JavaScript XML)
- React Components
- Server-side Rendering
- Event handling
- One-way Data Binding
- Simplicity and composable
- High Performance
What is the difference between real DOM and virtual DOM?
DOM stands for Document Object Model, and it is a mechanism for programs to access and update the structure, style, and contents of a document.
- Real DOM, also called browser DOM or HTML DOM, treats a document as a tree with its elements being nodes. Yet, real DOM is very inefficient and hard to manage.
- Virtual DOM is an abstract form of real DOM, a more lightweight one. All ReactJS reviews mention the fact that React uses virtual DOM as its ultimate advantage
Can you explain JSX?
JSX is a contraction of the JavaScript XML. It uses the expressiveness of JavaScript for making the HTML code easily understandable. JSX files make applications robust while boosting their performance.
A code example of JSX is:
class App extends React.Component {Â
 render() {Â
   return(Â
     <div>Â
       <h1>Hello Everyone</h1>Â
     </div>Â
   )Â
 }Â
}Â
Can browsers read a JSX file and Why?
No, Browsers cannot read JSX directly because they can only understand JavaScript objects, and JSX is not a regular JavaScript object. to make a browser read a JSX file, it has to be transformed to a JavaScript object using JSX transformers, and only then it can be fed into the browser for further use in the pipeline.
Why do we use render() in React?
In React, each component must have a render() function. It returns a single React element, which is, in fact, the representation of the native DOM component.
When there is a need for more than one HTML element to be rendered, we group them in one enclosing tag, which can be,or some other tag. There is a need for the render() function to return the same result each time it is invoked i.e. it needs to be kept pure.
For Example: If you need to display a heading, you can do this as below.
import React from 'react'Â
class App extends React.Component {Â
  render (){Â
     return (Â
        <h1>Hello World !</h1>Â
     )Â
  }Â
}Â
export default AppÂ
What are the various lifecycle methods of React components?
The lifecycle of the component is divided into four phases. Each phase contains some lifecycle methods that are specific to the particular phase.
- Initial Phase
- getDefaultProps() – It is used to specify the default value of this.props. It is invoked before the creation of the component or any props from the parent is passed into it.
- getInitialState() – It is used to specify the default value of this.state. It is executed before the creation of the component.
- Mounting Phase
- 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.
- render() – This method is defined in each and every component. It is responsible for returning a single root HTML node element. If you don’t want to render anything, you can return a null or false value.
- Updating Phase
- componentWillRecieveProps() – It is invoked when a component receives new props. 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. It allows you to control the component’s behavior of updating itself. If this method returns true, the component will update. Otherwise, the component will skip the updating.
- componentWillUpdate() – It is invoked just before the component updating occurs. Here, you can’t change the component state by invoking this.setState() method. It will not be called, if shouldComponentUpdate() returns false.
- render() – It is invoked to examine this.props and this.state and return one of the following types: React elements, Arrays and fragments, Booleans or null, String and Number. If shouldComponentUpdate() returns false, the code inside render() will be invoked again to ensure that the component displays itself properly.
- componentDidUpdate() – It is invoked immediately after the component updating occurs. In this method, you can put any code inside this which you want to execute once the updating occurs. This method is not invoked for the initial render.
- Unmounting Phase
- componentWillUnmount() – This method is invoked immediately before a component is destroyed and unmounted permanently. It performs any necessary cleanup related task 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.
What are states in React?
States in react acts as a source of data and are kept simple so that the objects which determine component rendering and behaviour become mutable other than props and develop a dynamic and interactive component.
What is the significance of keys in React?
Key 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.
What do you know about Props in React?
Prop is a contraction for Properties in React. Props is referred to the properties in React, including immutable, child components, parent component, etc. These read-only components need to be kept immutable i.e. pure. Throughout the application, props are passed down from the parent components to the child components.
In order to maintain the unidirectional data flow, a child component is restricted from sending a prop back to its parent component. This also helps in rendering the dynamically generated data.
Explain, how does the state differ from props in React?
- Changes inside child components are possible with props but not with state
- Changes inside the component aren’t possible with props but with state
- Props allow for a parent component to change the value, state doesn’t
How will you distinguish Redux from Flux?
- Components – React components subscribe to the store in flux whereas in redux, container components utilize connect
- Dispatcher – There is no dispatcher in redux. On the other hand, flux has a singleton dispatcher
- Number of Stores – While flux has several stores, there is only a single store for redux
- State – It is mutable for flux but immutable for redux
- Store – Influx, the store contains state as well as change logic. Contrary to this, the store in redux is separate from the change logic
- Store Type – All stores in flux are disconnected and flat. This is not the case with redux, where there is a single store with hierarchical reducers
Can you explain 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.
Can you explain Synthetic Events in React?
The Synthetic Events in React are the objects in React, which acts as a cross-browser wrapper around the browser’s native event. The main purpose is to combine the different browsers on the API so that the event shows various properties.
In the given example, e is a Synthetic event.
function ActionLink() {Â
   function handleClick(e) {Â
       e.preventDefault();Â
       console.log('You had clicked a Link.');Â
   }Â
   return (Â
       <a href="#" onClick={handleClick}>Â
             Click_MeÂ
       </a>Â
   );Â
}Â
Can you explain HOC?
HOC stands for Higher-Order Component. It is an advanced way of reusing the component logic, which wraps another component along with it.
You can do many tasks with HOC, some of them are given below:
- Code Reusability
- Props manipulation
- State manipulation
- Render hijacking
Can you define Refs in React?
‘Refs’ is short for references in React. Refs are used to store a reference to a single React element or a React component. This is later returned using the render function.
What is the use of Refs?
The Ref in React is used in the following cases:
- It is used to return a reference to the element.
- It is used when we need DOM measurements such as managing focus, text selection, or media playback.
- It is used in triggering imperative animations.
- It is used when integrating with third-party DOM libraries.
- It can also use as in call-backs.0
What do you know about components in React?
Component is one of the core building blocks of React. They serve the same purpose as JavaScript functions, but work in isolation and returns HTML via a render function. Components come in two types, Class components and Function components.
Can you provide example for Class components and Function components?
Class Components:
class Greeting extends React.Component {
 render() {
   return <h1>{`Hello, ${this.props.message}`}</h1>
 }
}
Function Components:
function Greeting({ message }) {
 return <h1>{`Hello, ${message}`}</h1>
}
What are the primary purpose of props in React?
React Props are like function arguments in JavaScript and attributes in HTML, they passes components via HTML attributes.
Primary purpose of props in React
- Pass custom data to component.
- Trigger state changes.
- Use via props.reactProp inside component’s render() method.
How will you pass a parameter to an event handler?
We can use can use an arrow function
<button onClick={() => this.handleClick(id)} />
How will you create refs?
We can create refs by two approaches
class MyComponent extends React.Component {
 constructor(props) {
   super(props)
   this.myRef = React.createRef()
 }
 render() {
   return <div ref={this.myRef} />
 }
}
class SearchBar extends Component {
  constructor(props) {
     super(props);
     this.txtSearch = null;
     this.state = { term: '' };
     this.setInputSearchRef = e => {
        this.txtSearch = e;
     }
  }
  onInputChange(event) {
     this.setState({ term: this.txtSearch.value });
  }
  render() {
     return (
        <input
           value={this.state.term}
           onChange={this.onInputChange.bind(this)}
           ref={this.setInputSearchRef} />
     );
  }
}
Can you explain the difference between Shadow DOM and Virtual DOM?
Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components whereas Virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.
What do you know about controlled components?
Controlled component is a way that you can handle the form input value using the state and to change the input value there is only one way to change it is using setState or useState
Example
Writing all names in Upper Case
handleChange(event) {
 this.setState({value: event.target.value.toUpperCase()})
}
What do you know about uncontrolled components?
Uncontrolled component is like traditional HTML, they are the ones that store their own state internally, and you query the DOM using a ref to find its current value when you need it.
Example using react hooks (useRef):
import React, { useRef } from "react";
export default function App() {
 const inputRef = useRef(null);
 const handleSubmitButton = () => {
   alert(inputRef.current.value);
 };
 return (
   <div className="App">
     <input type="text" ref={inputRef} />
     <input type="submit" value="submit" onClick={handleSubmitButton} />
   </div>
 );
}
How will you write comments in React
The comments in React/JSX are wrapped in curly braces.
Single-line comments:
<div>
 {/* Single-line comments */}
 {`Welcome ${user}, let's play React`}
</div>
Multi-line comments:
<div>
 {/* First line
  Second line */}
 {`Welcome ${user}, let's play React`}
</div>
How will call function when the component renders?
pass the function itself without parenthesis:
render() {
 return <button onClick={this.handleClick}>{'Click Me'}</button>
}
Why should we use className over class attribute in React?
class is a keyword in JavaScript, and JSX is an extension of JavaScript. That’s the principal reason why React uses className instead of class.
What is React Router and Why do we need a Router in React?
React Router is a standard routing library system built on top of the React. It is used to create Routing in the React application using React Router Package. It helps you to define multiple routes in the app. It provides the synchronous URL on the browser with data that will be displayed on the web page. It maintains the standard structure and behaviour of the application and mainly used for developing single page web applications. We need a Router to React so that we could define the multiple routes whenever the user types a particular URL. This way, the application of a particular router can be made when the URL matches the path defined inside the router.
What are the advantages of React Router?
Advantages of React Router:
- In this, it is not necessary to set the browser history manually.
- Link uses to navigate the internal links in the application. It is similar to the anchor tag.
- It uses Switch feature for rendering.
- The Router needs only a Single Child element.
- In this, every component is specified in <Route>.
- The packages are split into three packages, which are Web, Native, and Core. It supports the compact size of the React application.
What is various style in the React Component?
We can style React Component in mainly four ways
- Inline Styling
- CSS Stylesheet
- CSS Module
- Styled Components
What are keys in React? What is the syntax of Keys?
Keys are used in React to check all items and to track changes actively. They are used to directly check if an item has been added or removed from a list.
Consider the following syntax:
function List ({ todos }) {
return (
<ul>
{todos.map(({ task, id} ) => <li key={id}>{task}</li>}
</ul>
)
}
What is the difference between controlled and uncontrolled components?
Controlled component: it is a component over which React has complete control. It is the singular point of data for the forms.
Uncontrolled component: It is one where the form data gets handled by DOM and not the React component. This is usually done using refs in React.
What is the difference between cloneElement and createElement in React?
cloneElement is primarily used to clone an element and pass it to new props directly. Whereas, createElement is the entity that JSX gets compiled into. This is also used to create elements in React.
Who uses React?
Top companies are using React. There are
- Facebook
- Uber
- Udemy
- Instagram
- Airbnb
- Whatsup
- Amzon
- Twitter
- Pinterest
- yahoo
- Netflix, and so on
What are the Pros and Cons of React?
Pros:
- Easy to Learn and Easy to use
- Easy to Create Dynamic Web Applications
- Reusable Components
- Performance Enhancement
- The Support of Handy Tools
- SEO Friendly
- The Benefit of Having JavaScript Library
- Scope for Testing the Codes
Cons:
- The high pace of development
- Poor Documentation
- View Part
- JSX as a barrie