Crazy tech nerd

Original: www.edureka.co/blog/interv…

If you’re an aspiring front-end programmer preparing for an interview, this article is for you. This article is the perfect guide to what you need to learn and interview React.

JavaScript tools slowly but steadily took hold in the market, and demand for React grew exponentially. Choosing the right technology to develop an application or website is becoming increasingly challenging. React is considered the fastest growing Javascript framework.

As of today, there are about 1,000 contributors on Github. Unique features such as the Virtual DOM and reusable components have caught the attention of front-end developers. Even though it’s just a library of views in MVC (Model-View-Controller), it poses a strong challenge to Angular, Meteor, Vue, and other comprehensive frameworks. Below is the trend of popular JS frameworks:

Trends in JS frameworks

The React interview questions

Here are the top 50 React interview questions and answers interviewers are most likely to ask. To help you learn, I’ve categorized them:

  • Basic knowledge of
  • The React components
  • React Redux
  • The React routing

Basic knowledge of

1. Distinguish the Real DOM from the Virtual DOM

Real DOM Virtual DOM
1. Slow update. 1. Faster updates.
2. You can update HTML directly. 2. HTML cannot be updated directly.
3. If the element is updated, create a new DOM. 3. Update JSX if the element is updated.
4. DOM operation is expensive. DOM operation is very simple.
5. Too much memory is consumed. 5. Minimal memory consumption.

2. What is React?

  • React is a front-end JavaScript library developed by Facebook in 2011.
  • It follows a component-based approach and helps build reusable UI components.
  • It is used to develop complex and interactive Web and mobile UIs.
  • Although it was only open source in 2015, there is a large support community.

3. What’s the characteristic of React?

React’s main functions are as follows:

  1. It uses the virtual DOM instead of the real DOM.
  2. It can be rendered with server side.
  3. It follows one-way data flow or data binding.

4. List some of the main advantages of React.

Some of the main advantages of React are:

  1. It improves application performance
  2. It can be easily used on both the client and server side
  3. Thanks to JSX, the code is very readable
  4. React is easy to integrate with Other frameworks like Meteor, Angular, and so on
  5. With React, writing UI test cases becomes very easy

5. What are the limitations of React?

React’s limitations are as follows:

  1. React is a library, not a complete framework
  2. Its libraries are huge and take time to understand
  3. It can be difficult for a novice programmer to understand
  4. The coding is complicated because it uses inline templates and JSX

6. What is JSX?

JSX is short for J avaScript XML. Is a file used by React that takes advantage of JavaScript expressiveness and HTML-like template syntax. This makes the HTML file very easy to understand. This file can make your application very reliable and improve its performance. Here is an example of JSX:

render(){
    return(        
        <div>
            <h1> Hello World from Edureka!!</h1>
        </div>
    );
}
Copy the code

7. Do you know Virtual DOM? Explain how it works.

The Virtual DOM is a lightweight JavaScript object that is originally just a copy of the Real DOM. It is a tree of nodes that treats elements, their attributes, and their contents as objects and their attributes. React’s render function creates a tree of nodes from the React component. It then updates the tree in response to changes in the data model caused by various actions performed by the user or the system.

The Virtual DOM works in three simple steps.

  1. Every time the underlying data changes, the entire UI is rerendered in the Virtual DOM description.

  2. The differences between the previous DOM representation and the new representation are then calculated.

  3. When the calculation is complete, the Real DOM will be updated with only the actual changes.

8. Why can’t the browser read JSX?

Browsers can only handle JavaScript objects and cannot read JSX in regular JavaScript objects. So in order for the browser to be able to read JSX, you first need to convert the JSX file into a JavaScript object using a JSX converter like Babel, and then pass it to the browser.

9. How is the React ES6 grammar different from ES5?

The following syntax is different in ES5 and ES6:

  1. The require with the import
// ES5
var React = require('react');
 
// ES6
import React from 'react';
Copy the code
  1. The export and exports
// ES5
module.exports = Component;
 
// ES6
export default Component;
Copy the code
  1. The component and function
// ES5
var MyComponent = React.createClass({
    render: function() {
        return
			<h3>Hello Edureka!</h3>;
    }
});
 
// ES6
class MyComponent extends React.Component {
    render() {
        return
			<h3>Hello Edureka!</h3>;
    }
}
Copy the code
  1. props
// ES5
var App = React.createClass({
    propTypes: { name: React.PropTypes.string },
    render: function() {
        return
			<h3>Hello, {this.props.name}!</h3>;
    }
});

// ES6
class App extends React.Component {
    render() {
        return
			<h3>Hello, {this.props.name}!</h3>;
    }
}
Copy the code
  1. state
// ES5
var App = React.createClass({
    getInitialState: function() {
        return { name: 'world' };
    },
    render: function() {
        return
	        <h3>Hello, {this.state.name}!</h3>;
    }
});

// ES6
class App extends React.Component {
    constructor() {
        super();
        this.state = { name: 'world' };
    }
    render() {
        return
	        <h3>Hello, {this.state.name}!</h3>;
    }
}
Copy the code

How is React different from Angular?

The theme React Angular
1. Architecture There are only views in MVC Complete the MVC
2. Apply colours to a drawing You can render on the server side Client rendering
3. DOM The use of virtual DOM Using real DOM
4. Data binding Unidirectional data binding Bidirectional data binding
5. Debugging Compile time debugging Runtime debugging
6. The author Facebook Google

The React components

11. You understand “In React, everything is components.”

Components are the building blocks of the React application UI. These components break the entire UI into small, independent and reusable parts. Each component is independent of the other without affecting the rest of the UI.

12. Explain the purpose of render() in React.

Each React component mandates that it must have a render(). It returns a React element, which is a representation of the native DOM component. If you want to render multiple HTML elements, you must combine them in a closed tag, such as

,

,

, and so on. This function must remain pure, that is, it must return the same result every time it is called.

13. How do I embed two or more components into a single component?

Components can be embedded into a component in the following ways:

class MyComponent extends React.Component{
    render(){
        return(          
			<div>
            	<h1>Hello</h1>
                <Header/>
            </div>
        );
    }
}
class Header extends React.Component{
    render(){
        return
			<h1>Header Component</h1>   
   };
}
ReactDOM.render(
    <MyComponent/>, document.getElementById('content')
);
Copy the code

14. What is Props?

Props is short for the attribute in React. They are read-only components and must remain pure, that is, immutable. They are always passed from parent component to child component throughout the application. A child component can never send a prop back to its parent. This helps maintain a one-way data flow and is often used to render dynamically generated data.

15. What is the state in React? How is it used?

State is the core of the React component, the source of data, and must be as simple as possible. Basically state is an object that determines the presentation and behavior of a component. Unlike props, they are mutable and create dynamic and interactive components. They can be accessed via this.state().

Distinguish between states and props

conditions State Props
1. Receives the initial value from the parent component Yes Yes
2. The parent component can change the value No Yes
3. Set default values for each component Yes Yes
4. Changes within the component Yes No
5. Set the initial value of the sub-component Yes Yes
6. Internal changes to the child component No Yes

17. How do I update the component status?

You can update the state of a component with this.setState().

class MyComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            name: 'Maxx',
            id: '101'
        }
    }
    render()
        {
            setTimeout(()=>{this.setState({name:'Jaeha', id:'222'})},2000)
            return (              
				<div>
                	<h1>Hello {this.state.name}</h1>
					<h2>Your Id is {this.state.id}</h2>
                </div>
            );
        }
    }
ReactDOM.render(
    <MyComponent/>, document.getElementById('content')
);
Copy the code

18. What is the arrow function in React? How does it work?

Arrow functions (=>) are short syntax for writing function expressions. These functions allow the context of the component to be bound correctly, since automatic binding is not available by default in ES6. Arrow functions are useful when using higher-order functions.

//General way
render() {    
    return(
        <MyInput onChange = {this.handleChange.bind(this) } />
    );
}
//With Arrow Function
render() {  
    return(
        <MyInput onChange = { (e)=>this.handleOnChange(e) } />
    );
}
Copy the code

Distinguish between stateful and stateless components.

Stateful component Stateless component
1. Store information about component status changes in memory 1. Calculate the internal status of the component
2. The right to change the status 2. No right to change the status
3. Include past, present, and possible future state changes 3. It does not include past, present and possible future state changes
4. Receive notification of the stateless component’s state change requirement and send them props. 4. Receive props from the stateful component and treat it as a callback function.

20. What are the phases of the React component lifecycle?

The React component lifecycle has three distinct phases:

  1. * Initial render phase: * This is the phase where the component is about to begin its life journey and enter the DOM.
  2. * Update phase: * Once a component has been added to the DOM, it is only possible to update and re-render if prop or state changes. This only happens at this stage.
  3. * Uninstall phase: * This is the final phase of the component’s life cycle, when the component is destroyed and removed from the DOM.

21. Explain the React component lifecycle approach in detail.

Some of the most important lifecycle approaches are:

  1. componentWillMount**()** – Executed before rendering, on both the client and server side.
  2. componentDidMount**()** – Only performed on the client after the first render.
  3. componentWillReceiveProps**()** – Called when the props are received from the parent class and before calling another renderer.
  4. shouldComponentUpdate**()** – Returns true or false depending on the specific condition. If you want to update the component, please returntrueOtherwise returnsfalse. By default, it returns false.
  5. componentWillUpdate**()** – called before rendering in the DOM.
  6. componentDidUpdate**()** – called immediately after rendering occurs.
  7. componentWillUnmount**()** – called after the component is uninstalled from the DOM. Use to clear memory space.

22. What happens in React?

In React, an event is a trigger response to a specific action such as a mouse hover, mouse click, keystroke, etc. Handling these events is similar to handling events in DOM elements. But there are some grammatical differences, such as:

  1. Use the hump nomenclature to name events instead of using lowercase letters only.
  2. Events are passed as functions, not strings.

Event parameters re – contain a set of properties specific to the event. Each event type contains its own properties and behavior that can only be accessed through its event handler.

How to create an event in React?

class Display extends React.Component({    
    show(evt) {
        // code   
    },   
    render() {      
        // Render the div with an onClick prop (value is a function)        
        return (            
            <div onClick={this.show}>Click Me!</div>
        );    
    }
});
Copy the code

24. What are synthetic events in React?

Synthetic events are objects that act as cross-browser wrappers around browser native events. They combine the behavior of different browsers into a single API. This is done to ensure that events display consistent properties across browsers.

What do you know about Refs in React?

Refs is short for reference in React. It is a property that helps store references to a particular React element or component and is returned by the component render configuration function. Used for references to specific elements or components returned by Render (). They come in handy when you need to take DOM measurements or add methods to components.

class ReferenceDemo extends React.Component{
     display() {
         const name = this.inputDemo.value;
         document.getElementById('disp').innerHTML = name;
     }
render() {
    return(        
          <div>
            Name: <input type="text" ref={input => this.inputDemo = input} />
            <button name="Click" onClick={this.display}>Click</button>            
            <h2>Hello <span id="disp"></span> !!!</h2>
          </div>
    );
   }
 }
Copy the code

26. List some cases where Refs should be used.

Here are the cases where refS should be used:

  • Need to manage focus, select text, or play media
  • Triggered animation
  • Integrate with third-party DOM libraries

How to modularize the code in React?

You can use the export and import properties to modularize your code. They help to write components separately in different files.

//ChildComponent.jsx export default class ChildComponent extends React.Component { render() { return( <div> <h1>This is a child component</h1> </div> ); } } //ParentComponent.jsx import ChildComponent from './childcomponent.js'; class ParentComponent extends React.Component { render() { return( <div> <App /> </div> ); }}Copy the code

28. How to create forms in React

React forms are similar to HTML forms. But in React, state is included in the component’s state property and can only be updated with setState(). Therefore, elements cannot update their state directly; their submission is handled by JavaScript functions. This function gives full access to the data that the user entered into the form.

handleSubmit(event) { alert('A name was submitted: ' + this.state.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleSubmit} /> </label> <input type="submit" value="Submit"  /> </form> ); }Copy the code

29. What do you know about controlled and uncontrolled components?

The controlled components Uncontrolled component
1. Not maintaining yourself 1. Keep your groove on
2. Data is controlled by the parent component 2. Data is controlled by DOM
3. Get the current value via props and notify the change via a callback 3. Refs is used to obtain the current value

30. What is a high-level component?

Higher-order components are high-level ways of reusing component logic and are a component pattern derived from React. HOC is a custom component that contains another component within it. They can accept any dynamics provided by their children, but do not modify or copy any behavior in their input components. You can think of HOC as a “Pure” component.

31. What can you do with HOC?

HOC can be used for many tasks, such as:

  • Code reuse, logic and bootstrap abstractions
  • Rendering hijacked
  • State abstraction and control
  • Props to control

32. What are pure components?

Pure components are the simplest and fastest components that can be written. They can replace any render() -only component. These components enhance code simplicity and application performance.

33. What is the importance of key in React?

The key identifies the unique Virtual DOM element and the corresponding data that drives the UI. They help React optimize rendering by recycling all the current elements in the DOM. These keys must be unique numbers or strings. React simply reorders elements rather than rerendering them. This can improve application performance.

React Redux

34. What are the main problems with the MVC framework?

Here are some of the main issues with the MVC framework:

  • DOM manipulation is very costly
  • The program is slow and inefficient
  • Serious waste of memory
  • Because of circular dependencies, component models need to be created around Models and views

35. Explain Flux

36. What is Redux?

Redux is one of the hottest front-end development libraries out there today. It is a predictable state container for JavaScript programs and is used for state management of the entire application. Applications developed using Redux are easy to test, can run in different environments, and show consistent behavior.

37. What are the three principles that Redux follows?

  1. *** Single fact source: *** The state of the entire application is stored in a single store object/state tree. A single state tree makes it easier to track changes over time and debug or examine applications.
  2. *** States are read-only: *** The only way to change a state is to trigger an action. Actions are normal JS objects that describe changes. Just as state is the minimum representation of the data, this operation is the minimum representation of changes to the data.
  3. *** Make changes using pure functions: *** In order to specify how the state tree is transformed by operations, you need pure functions. Pure functions are those whose return value depends only on the value of their arguments.

38. What is your understanding of “single source of fact”?

Redux uses the “Store” to Store the entire state of a program in one place. So the state of all components is stored in the Store, and they receive updates from the Store itself. A single state tree makes it easier to track changes over time and debug or examine programs.

List the components of Redux.

Redux consists of the following components:

  1. Action – This is an object that describes what has happened.
  2. Reducer – This is the place to determine how the state will change.
  3. Store – The state/object tree of the entire program is stored in the Store.
  4. View – Displays only data provided by the Store.

40. How does data flow through Redux?

41. How to define an Action in Redux?

Actions in React must have a type attribute, which indicates the type of Action being executed. You must define them as string constants, and you can add more attributes to them. In Redux, the action is created by the function called Action Creators. Here is an example of Action and Action Creator:

function addTodo(text) {
       return {
                type: ADD_TODO,    
                 text
    }
}
Copy the code

42. Explain the functions of Reducer.

Reducers are pure functions that specify how the state of an application changes in response to an ACTION. Reducers works by accepting the previous state and action, and then it returns a new state. It determines what kind of update needs to be performed based on the type of operation and then returns the new value. If there is no need to complete the task, it returns to its original state.

43. What is the meaning of Store in Redux?

A Store is a JavaScript object that holds the state of a program and provides methods to access the state, schedule operations, and register listeners. The entire state/object tree of an application is held in a single store. As a result, Redux is very simple and predictable. We can pass middleware to the Store to process the data and record the various actions that change the state of the store. All operations return a new state via reducer.

44. What is the difference between Redux and Flux?

Flux Redux
1. Store contains state and change logic 1. Store and change logic are separate
2. Multiple stores 2. Only one Store
3. All stores are independent and flat 3. Single Store with layered Reducer
4. Have a single scheduler 4. No concept of a scheduler
5. React Component subscription Store 5. Container components are related
6. State is variable 6. States are immutable

45. What are the advantages of Redux?

The advantages of Redux are as follows:

  • Predictability of results – Since there is always a real source, the Store, there is no question of how to synchronize the current state with the action and other parts of the application.
  • Maintainability – Code becomes more maintainable, with predictable results and strict structure.
  • Server side rendering – You just need to upload the store created on the server to the client. This is useful for initial rendering and can optimize application performance to provide a better user experience.
  • Developer tools – From actions to state changes, developers can track everything that happens in the application in real time.
  • Community and ecosystem – Redux has a huge community behind it, which makes it even more fascinating. A large community of talented people contributed to the improvements and developed various applications.
  • Easy to test – Redux’s code is primarily small, pure, and stand-alone functionality. This makes the code testable and independent.
  • Organization – Redux explains exactly how the code should be organized, which makes it more consistent and simple to use by the team.

The React routing

46. What is a React route?

React Routing is a powerful routing library built on top of React that helps add new screens and streams to your application. This keeps the URL in sync with the data displayed on the web page. It is responsible for maintaining standardized structure and behavior and is used to develop single-page Web applications. React routing has a simple API.

47. Why is the Switch keyword used in React Router V4?

While

** is used to encapsulate multiple routes in a Router, you can use the “switch” keyword when you want to display only a single route that you want to render among multiple defined routes. When used, the

** tag matches the defined urls to the defined routes in order. When the first match is found, it renders the specified path. To bypass other routes.

48. Why do you need routing in React?

A Router is used to define multiple routes. When a user defines a specific URL, if the URL matches the path of any route defined on the Router, the user is redirected to the specific route. So basically we need to add a Router library to our application that allows you to create multiple routes, each of which gives us a unique view

<switch> <route exact path= '/' component={Home}/> <route path= '/posts/:id' component={Newpost}/> <route path= '/posts' component={Post}/> </switch>Copy the code

49. List the advantages of the React Router.

Several advantages are:

  1. Just as React is based on components, in React Router V4, the API is‘All About Components’. You can visualize the Router as a single root component (<BrowserRouter>), where we place the specific child route (<route>) Wrap it up.
  2. No manual history setting: In React Router V4, all we did was wrap the route in a

    component.
  3. Packages are separate: there are three packages, one for Web, one for Native, and one for Core. This makes our application more compact. It’s easy to switch based on similar coding styles.

50. How is the React Router different from the regular route?

The theme Conventional routing The React routing
Participating pages Each view corresponds to a new file Only a single HTML page is involved
The URL to change The HTTP request is sent to the server and the corresponding HTML page is received Change only the history properties
experience The user actually switches between different pages in each view Users think they are switching between different pages

Hopefully, the React interview questions and answers will help you prepare for the interview. All the best!

Welcome to pay attention to jingchengyideng public number: Jingchengyideng, get more front dry goods.