Skip to content

Latest commit

 

History

History
2566 lines (1682 loc) · 93.6 KB

react.md

File metadata and controls

2566 lines (1682 loc) · 93.6 KB

React

What is the use of refs?

What is JEST?

What are the advantages of ReactJS?

How to write comments in ReactJS?

What is context?

What is virtual DOM?

How does React work?

What is React?

What is props in ReactJS?

What are the major features of ReactJS?

What is ReactJS?

What are props in React?

How would you write an inline style in React?

What are the limitations of ReactJS?

What’s the difference between an "Element" and a "Component" in React?

What are stateful components?

What are stateless components?

What are portals in ReactJS?

What are fragments?

Why is it necessary to capitalize the components?

What is reconciliation?

What is the purpose of using super constructor with props argument?

When to use a Class Component over a Functional Component?

What are the advantages of using React?

What are Higher-Order components?

What are controlled components?

What is the difference between a Presentational component and a Container component?

How to create refs?

What are the differences between a class component and functional component?

What do you like about React?

What is inline conditional expressions?

What is the difference between state and props?

How is React different from AngularJS (1.x)?

What happens during the lifecycle of a React component?

How to pass a parameter to an event handler or callback?

What is the purpose of callback function as an argument of setState?

What is the difference between component and container in react Redux?

What is the difference between state and props?

What is state in ReactJS?

How to create components in ReactJS?

What is the difference between Element and Component?

What are refs used for in React?

When rendering a list what is a key and what is it's purpose?

What is JSX?

Where in a React component should you make an AJAX request?

What is the difference between React Native and React?

Describe how events are handled in React.

What is Flux?

Where is the state kept in a React + Redux application?

What is the point of Redux?

What is Flow?

How do we pass a property from a parent component props to a child component?

What is JSX?

How error boundaries handled in React (15)?

What does it mean for a component to be mounted in React?

What happens when you call "setState"?

What happens when you call setState?

What's the difference between a controlled component and an uncontrolled one in React?

How would you prevent a component from rendering in React?

How do you prevent the default behavior in an event callback in React?

What is Key and benefit of using it in lists?

What's an alternative way to avoid having to bind to this in event callback methods?

What is the point of using keys in React?

What's the typical pattern for rendering a list of components from an array of data?

What is the render method for?

What is reconciliation in React?

What's the difference between an Element and a Component in React?

What is the point of shouldComponentUpdate() method?

What are PropTypes in React?

What's the difference between a "smart" component and a "dumb" component?

What is ReactDOM?

What are typical middleware choices for handling asynchronous calls in Redux?

What's the typical flow of data like in a React + Redux app?

What is the difference between createElement and cloneElement?

Name the different lifecycle methods.

Given the code defined above, can you identify two problems?

What are stateless components?

What are Pure Components?

Name some popular Flux Libraries

Why should not we update the state directly?

What are controlled components?

What is the difference between HTML and React event handling?

How to bind methods or event handlers in JSX callbacks?

What can you tell me about JSX?

What are synthetic events in ReactJS?

What don't you like about React?

What are some limitations of things you shouldn't do in the component's render method?

What are forward refs?

What is the difference between ShadowDOM and VirtualDOM?

What is an action?

What are uncontrolled components?

What is the difference between createElement and cloneElement?

What is Lifting State Up in ReactJS?

What are the different phases of ReactJS component lifecycle?

What are the lifecycle methods of ReactJS?

What is a store in redux?

What is children prop?

What is state in react?

What is equivalent of the following using React.createElement?

How to set state with a dynamic key name?

What would be the common mistake of function being called every time the component renders?

What is JSX?

Why ReactJS uses className over class attribute?

Why fragments are better than container divs?

What does "shouldComponentUpdate" do and why is it important?

How would you prevent a component from rendering?

What is the alternative of binding this in the constructor?

Why is it advised to pass a callback function to setState as opposed to an object?

What advantages are using arrow functions?

What are error boundaries in ReactJS (16)?

What is a higher order component?

What are the advantages of React over VueJS?

How do you tell React to build in Production mode and what will that do?

Describe Flux vs MVC?

Are you familiar with Flux?

What is the second argument that can optionally be passed to setState and what is its purpose?

What is wrong with this code?

How to create props proxy for HOC component?

Why would you eject from create-react-app?

What are some recent changes in the React library (e.g. in version 14, 15)?

What is mapStateToProps and mapDispatchToProps?

What is "Children"?

What's a pure functional component in React?

Why does React use SyntheticEvents?

Why would you use React.Children.map(props.children, () => ) instead of props.children.map(() => )?

What is the difference between a controlled component and an uncontrolled component?

What is the difference between Flow and PropTypes?

What is the purpose of super(props)?

Why would you need to bind event handlers to "this"?

If you created a React element like Twitter below, what would the component definition of Twitter look like?

Which is preferred option with in callback refs and findDOMNode()?

Why are String Refs legacy?

How to apply validation on Props in ReactJS?

What is a reducer?

Why would you use forceUpdate in a React component?

What is React Fiber?

If you need to access the underlying DOM node for a React component, what's the typical way to do this in React?

What are the recommended ways for static type checking?

What is the difference between ReactJS and Angular?

What is the React context?

Explain the Virtual DOM concept in React.

What is reselect and how it works?

How to use Polymer in ReactJS?

What is a pure function?

Explain some difference between Flux and AngularJS (1.x) approach

What is React Fiber?

What is Redux Thunk used for?

What is the use of refs?

The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when we need direct access to DOM element or an instance of a component.

Source

[↑] Back to top

What is JEST?

Jest is a JavaScript unit testing framework made by Facebook based on Jasmine and provides automated mock creation and a jsdom environment. It's often used for testing React components.

Source

[↑] Back to top

What are the advantages of ReactJS?

Below are the advantages of ReactJS:

  1. Increases the application’s performance with Virtual DOM
  2. JSX makes code is easy to read and write
  3. It renders both on client and server side
  4. Easy to integrate with other frameworks (Angular, BackboneJS) since it is only a view library
  5. Easy to write UI Test cases and integration with tools such as JEST.
Source

[↑] Back to top

How to write comments in ReactJS?

The comments in ReactJS/JSX is similar to javascript multiline comments which are wrapped with curly braces:

Single-line comments:

<div>
  {/* Single-line comments */}
  Welcome {user}, Let's play React
</div>

Multi-line comments:

<div>
  {/* Multi-line comments for more than
   one line */}
  Welcome {user}, Let's play React
</div>
Source

[↑] Back to top

What is context?

Context provides a way to pass data through the component tree without having to pass props down manually at every level. For example, authenticated user, locale preference, UI theme need to be accessed in the application by many components.

const {Provider, Consumer} = React.createContext(defaultValue);
Source

[↑] Back to top

What is virtual DOM?

The virtual DOM (VDOM) is an in-memory representation of Real DOM. The representation of a UI is kept in memory and synced with the “real” DOM. It’s a step that happens between the render function being called and the displaying of elements on the screen. This entire process is called reconciliation.

Source

[↑] Back to top

How does React work?

React creates a virtual DOM. When state changes in a component it firstly runs a "diffing" algorithm, which identifies what has changed in the virtual DOM. The second step is reconciliation, where it updates the DOM with the results of diff.

Source

[↑] Back to top

What is React?

React is an open-source JavaScript library created by Facebook for building complex, interactive UIs in web and mobile applications. React’s core purpose is to build UI components; it is often referred to as just the “V” (View) in an “MVC” architecture.

Source

[↑] Back to top

What is props in ReactJS?

Props are inputs to a React component. They are single values or objects containing a set of values that are passed to React Components on creation using a naming convention similar to HTML-tag attributes. i.e, They are data passed down from a parent component to a child component.

The primary purpose of props in React is to provide following component functionality:

  1. Pass custom data to your React component.
  2. Trigger state changes.
  3. Use via this.props.reactProp inside component's render() method.

For example, let us create an element with reactProp property,

 <Element reactProp = "1" />

This reactProp (or whatever you came up with) name then becomes a property attached to React's native props object which originally already exists on all components created using React library.

 props.reactProp;
Source

[↑] Back to top

What are the major features of ReactJS?

The major features of ReactJS are as follows,

  • It uses VirtualDOM instead RealDOM considering that RealDOM manipulations are expensive.
  • Supports server-side rendering
  • Follows Unidirectional data flow or data binding
  • Uses reusable/composable UI components to develop the view
Source

[↑] Back to top

What is ReactJS?

ReactJS is an open-source frontend JavaScript library which is used for building user interfaces especifically for single page applications. It is used for handling view layer for web and mobile apps. React was created by Jordan Walke, a software engineer working for Facebook. ReactJS was first deployed on Facebook’s newsfeed in 2011 and on Instagram.com in 2012.

Source

[↑] Back to top

What are props in React?

Props are properties that are passed into a child component from its parent, and are readonly.

Source

[↑] Back to top

How would you write an inline style in React?

For example:

<div style={{ height: 10 }}>
Source

[↑] Back to top

What are the limitations of ReactJS?

Below are the list of limitations:

  1. React is just a view library, not a full-blown framework
  2. There is a learning curve for beginners who are new to web development.
  3. Integrating React.js into a traditional MVC framework requires some additional configuration
  4. The code complexity increases with inline templating and JSX.
  5. Too many smaller components leading to over-engineering or boilerplate
Source

[↑] Back to top

What’s the difference between an "Element" and a "Component" in React?

Simply put, a React element describes what you want to see on the screen. Not so simply put, a React element is an object representation of some UI.

A React component is a function or a class which optionally accepts input and returns a React element (typically via JSX which gets transpiled to a createElement invocation).

Source

[↑] Back to top

What are stateful components?

If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These Stateful components are always class components and have a state that gets initialized in the constructor.

class App extends Component {
 constructor(props) {
  super(props);
  this.state = { count: 0 };
 }

 render() {
    // omitted for brevity
  }
}
Source

[↑] Back to top

What are stateless components?

If the behaviour is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for stateless functional components. There are a lot of benefits if you decide to use stateless functional components here; they are easy to write, understand, and test, and you can avoid the this keyword altogether.

Source

[↑] Back to top

What are portals in ReactJS?

Portal is a recommended way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

ReactDOM.createPortal(child, container);

The first argument (child) is any renderable React child, such as an element, string, or fragment. The second argument (container) is a DOM element.

Source

[↑] Back to top

What are fragments?

It's common pattern in React which is used for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}

There is also a shorter syntax which is not supported in many tools

render() {
    return (
      <>
         <ChildA />
         <ChildB />
         <ChildC />
      </>
    );
  }
Source

[↑] Back to top

Why is it necessary to capitalize the components?

It is necessary because components are not the DOM element but they are constructors. If they are not capitalized, they can cause various issues and can confuse developers with several elements.

Source

[↑] Back to top

What is reconciliation?

When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called reconciliation.

Source

[↑] Back to top

What is the purpose of using super constructor with props argument?

A child class constructor cannot make use of this reference until super() method has been called. The same applies for ES6 sub-classes as well. The main reason of passing props parameter to super() call is to access this.props in your child constructors.

Passing props:

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        console.log(this.props);  // Prints { name: 'sudheer',age: 30 }
    }
}

Not passing props:

class MyComponent extends React.Component {
    constructor(props) {
        super();
        console.log(this.props); // Prints undefined
        // But Props parameter is still available
        console.log(props); // Prints { name: 'sudheer',age: 30 }
    }

    render() {
        // No difference outside constructor
        console.log(this.props) // Prints { name: 'sudheer',age: 30 }
    }
}

The above code snippets reveals that this.props behavior is different only with in the constructor. It would be same outside the constructor.

Source

[↑] Back to top

When to use a Class Component over a Functional Component?

If the component need state or lifecycle methods then use class component otherwise use functional component.

Source

[↑] Back to top

What are the advantages of using React?

  • It is easy to know how a component is rendered, you just need to look at the render function.
  • JSX makes it easy to read the code of your components. It is also really easy to see the layout, or how components are plugged/combined with each other.
  • You can render React on the server-side. This enables improves SEO and performance.
  • It is easy to test.
  • You can use React with any framework (Backbone.js, Angular.js) as it is only a view layer.
Source

[↑] Back to top

What are Higher-Order components?

A higher-order component (HOC) is a function that takes a component and returns a new component. Basically, it’s a pattern that is derived from React’s compositional nature We call them as “pure’ components” because they can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components.

const EnhancedComponent = higherOrderComponent(WrappedComponent);

HOC can be used for many use cases as below,

  1. Code reuse, logic and bootstrap abstraction
  2. Render High jacking
  3. State abstraction and manipulation
  4. Props manipulation
Source

[↑] Back to top

What are controlled components?

A ReactJS component that controls the input elements within the forms on subsequent user input is called “Controlled component”. i.e, every state mutation will have an associated handler function.

For example, to write all the names in uppercase letters, we use handleChange as below,

handleChange(event) {
    this.setState({
        value: event.target.value.toUpperCase()
    });
}
Source

[↑] Back to top

What is the difference between a Presentational component and a Container component?

  • Presentational components are concerned with how things look. They generally receive data and callbacks exclusively via props. These components rarely have their own state, but when they do it generally concerns UI state, as opposed to data state.

  • Container components are more concerned with how things work. These components provide the data and behavior to presentational or other container components. They call Flux actions and provide these as callbacks to the presentational components. They are also often stateful as they serve as data sources.

Source

[↑] Back to top

How to create refs?

Refs are created using React.createRef() method and attached to React elements via the ref attribute. In order to use refs throughout the component, just assign the ref to the instance property with in constructor.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

And:

class UserForm extends Component {
  handleSubmit = () => {
    console.log("Input Value is: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input) => this.input = input} /> // Access DOM input in handle submit
        <button type='submit'>Submit</button>
      </form>
    )
  }
}

We can also use it in functional components with the help of closures.

Source

[↑] Back to top

What are the differences between a class component and functional component?

  • Class components allows you to use additional features such as local state and lifecycle hooks. Also, to enable your component to have direct access to your store and thus holds state.

  • When your component just receives props and renders them to the page, this is a stateless component, for which a pure function can be used. These are also called dumb components or presentational components.

Source

[↑] Back to top

What do you like about React?

Source

[↑] Back to top

What is inline conditional expressions?

You can use either if statements or ternary expressions which are available from JS to conditionally render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator(&&).

<h1>Hello!</h1>
   {messages.length > 0 &&
<h2>
    You have {messages.length} unread messages.
</h2>
Source

[↑] Back to top

What is the difference between state and props?

The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events.

Props (short for properties) are a Component's configuration. They are received from above and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data - callback functions may be passed in as props.

Source

[↑] Back to top

How is React different from AngularJS (1.x)?

For example, AngularJS (1.x) approaches building an application by extending HTML markup and injecting various constructs (e.g. Directives, Controllers, Services) at runtime. As a result, AngularJS is very opinionated about the greater architecture of your application — these abstractions are certainly useful in some cases, but they come at the cost of flexibility.

By contrast, React focuses exclusively on the creation of components, and has few (if any) opinions about an application’s architecture. This allows a developer an incredible amount of flexibility in choosing the architecture they deem “best” — though it also places the responsibility of choosing (or building) those parts on the developer.

Source

[↑] Back to top

What happens during the lifecycle of a React component?

At the highest level, React components have lifecycle events that fall into three general categories:

  1. Initialization
  2. State/Property Updates
  3. Destruction

Source

[↑] Back to top

How to pass a parameter to an event handler or callback?

You can use an arrow function to wrap around an event handler and pass parameters:

<button onClick={() => this.handleClick(id)} />

This is equivalent to calling .bind as below,

<button onClick={this.handleClick.bind(this, id)} />
Source

[↑] Back to top

What is the purpose of callback function as an argument of setState?

The callback function is invoked when setState finished and the component gets rendered. Since setState is asynchronous the callback function is used for any post action.

Note: It is recommended to use lifecycle method rather this callback function.

setState({name: 'sudheer'}, () => console.log('The name has updated and component re-rendered'));
Source

[↑] Back to top

What is the difference between component and container in react Redux?

Component is part of the React API. A Component is a class or function that describes part of a React UI. Container is an informal term for a React component that is connected to a redux store. Containers receive Redux state updates and dispatch actions, and they usually don't render DOM elements; they delegate rendering to presentational child components.

Source

[↑] Back to top

What is the difference between state and props?

Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to component. i.e,

  • Props get passed to the component similar to function parameters
  • state is managed within the component similar to variables declared within a function.
Source

[↑] Back to top

What is state in ReactJS?

State of a component is an object that holds some information that may change over the lifetime of the component. We should always try to make our state as simple as possible and minimize the number of stateful components.

Let's create user component with message state,

class User extends React.Component {
   constructor(props) {
      super(props);

      this.state = {
         message: "Welcome to React world",
      }
   }
   render() {
      return (
         <div>
            <h1>{this.state.message}</h1>
         </div>
      );
   }
}
Source

[↑] Back to top

How to create components in ReactJS?

There are two possible ways to create ReactJS Components.

  1. Functional components: This is the simplest way to create ReactJS components. It accepts props as an Object and returns ReactJS elements. We call it as “functional” because those are pure JavaScript functions.
	function Greeting(props) {
   	   return <h1> Hello, {props.message}</h1>
	}
  1. Class components: You can also use Es6 class to define component. The above functional component can be written as below,
      class Greeting extends React.Component {
  	    render() {
    		    return <h1>Hello, {this.props.message}</h1>;
  	        }
	    }
Source

[↑] Back to top

What is the difference between Element and Component?

An element is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other elements in their props. Creating a React element is cheap. Once an element is created, it is never mutated. The object representation of React element would be as follows,

const element = React.createElement(
  'div',
  {id: 'login-btn'},
  'Login'
)

The above createElement returns as object as below,

{
  type: 'div',
  props: {
    children: 'Login',
    id: 'login-btn'
  }
}

And finally it renders to the DOM using ReactDOM.render as below,

<div id='login-btn'>Login</div>

Whereas a component can be declared in several different ways. It can be a class with a render() method. Alternatively, in simple cases, it can be defined as a function. In either case, it takes props as an input, and returns an element tree as the output. JSX transpiled as createElement at the end.

function Button ({ onLogin }) {
  return React.createElement(
    'div',
    {id: 'login-btn', onClick: onLogin},
    'Login'
  )
}
Source

[↑] Back to top

What are refs used for in React?

Refs are an escape hatch which allow you to get direct access to a DOM element or an instance of a component. In order to use them you add a ref attribute to your component whose value is a callback function which will receive the underlying DOM element or the mounted instance of the component as its first argument.

class UnControlledForm extends Component {
  handleSubmit = () => {
    console.log("Input Value: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input) => this.input = input} />
        <button type='submit'>Submit</button>
      </form>
    )
  }
}

Above notice that our input field has a ref attribute whose value is a function. That function receives the actual DOM element of input which we then put on the instance in order to have access to it inside of the handleSubmit function.

It’s often misconstrued that you need to use a class component in order to use refs, but refs can also be used with functional components by leveraging closures in JavaScript.

function CustomForm ({handleSubmit}) {
  let inputElement
  return (
    <form onSubmit={() => handleSubmit(inputElement.value)}>
      <input
        type='text'
        ref={(input) => inputElement = input} />
      <button type='submit'>Submit</button>
    </form>
  )
}
Source

[↑] Back to top

When rendering a list what is a key and what is it's purpose?

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.

render () {
  return (
    <ul>
      {this.state.todoItems.map(({task, uid}) => {
        return <li key={uid}>{task}</li>
      })}
    </ul>
  )
}

Most often you would use IDs from your data as keys. When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort. It is not recommend to use indexes for keys if the items can reorder, as that would be slow.

Source

[↑] Back to top

What is JSX?

JSX is a syntax notation for JavaScript XML(XML-like syntax extension to ECMAScript). It stands for JavaScript XML. It provides expressiveness of JavaScript along with HTML like template syntax. For example, the below text inside h1 tag return as javascript function to the render function,

   render(){
    	return(
         <div>
            <h1> Welcome to React world!!</h1>
         </div>
    	);
     }
Source

[↑] Back to top

Where in a React component should you make an AJAX request?

componentDidMount is where an AJAX request should be made in a React component.

This method will be executed when the component “mounts” (is added to the DOM) for the first time. This method is only executed once during the component’s life. Importantly, you can’t guarantee the AJAX request will have resolved before the component mounts. If it doesn't, that would mean that you’d be trying to setState on an unmounted component, which would not work. Making your AJAX request in componentDidMount will guarantee that there’s a component to update.

Source

[↑] Back to top

What is the difference between React Native and React?

  • ReactJS is a JavaScript library, supporting both front end web and being run on the server, for building user interfaces and web applications.

  • React Native is a mobile framework that compiles to native app components, allowing you to build native mobile applications (iOS, Android, and Windows) in JavaScript that allows you to use ReactJS to build your components, and implements ReactJS under the hood.

Source

[↑] Back to top

Describe how events are handled in React.

In order to solve cross browser compatibility issues, your event handlers in React will be passed instances of SyntheticEvent, which is React’s cross-browser wrapper around the browser’s native event. These synthetic events have the same interface as native events you’re used to, except they work identically across all browsers.

What’s mildly interesting is that React doesn’t actually attach events to the child nodes themselves. React will listen to all events at the top level using a single event listener. This is good for performance and it also means that React doesn’t need to worry about keeping track of event listeners when updating the DOM.

Source

[↑] Back to top

What is Flux?

Unidrectional application flow paradigm popular a few years back in React; mostly superceded by Redux these days.

Source

[↑] Back to top

Where is the state kept in a React + Redux application?

In the store.

Source

[↑] Back to top

What is the point of Redux?

Application state management that is easy to reason about, maintain and manage in an asynchronous web application environment.

Source

[↑] Back to top

What is Flow?

Flow is a static type checker, designed to find type errors in JavaScript programs, created by Facebook. Flow types can express much more fine-grained distinctions than traditional type systems. For example, Flow helps you catch errors involving null, unlike most type systems.

Source

[↑] Back to top

How do we pass a property from a parent component props to a child component?

For example:

<ChildComponent someProp={props.someProperty} />
Source

[↑] Back to top

What is JSX?

JSX is JavaScript with extensions. Useful for creating React elements with the full power of JavaScript. Not required for a React app, but typically it's used.

Source

[↑] Back to top

How error boundaries handled in React (15)?

React15 provided very basic support for error boundaries using the method name unstable_handleError. Later this has been renamed as componentDidCatch starting from React16 beta release.

Source

[↑] Back to top

What does it mean for a component to be mounted in React?

It has a corresponding element created in the DOM and is connected to that.

Source

[↑] Back to top

What happens when you call "setState"?

The first thing React will do when setState is called is merge the object you passed into setState into the current state of the component. This will kick off a process called reconciliation. The end goal of reconciliation is to, in the most efficient way possible, update the UI based on this new state.

To do this, React will construct a new tree of React elements (which you can think of as an object representation of your UI). Once it has this tree, in order to figure out how the UI should change in response to the new state, React will diff this new tree against the previous element tree.

By doing this, React will then know the exact changes which occurred, and by knowing exactly what changes occurred, will able to minimize its footprint on the UI by only making updates where absolutely necessary.

Source

[↑] Back to top

What happens when you call setState?

The state property is updated in a React component with the object passed into setState, and this is done asynchronously. It tells React that this component and its children need to be re-rendered, but React may not do this immediately (it may batch these state update requests for better performance).

Source

[↑] Back to top

What's the difference between a controlled component and an uncontrolled one in React?

  • A controlled component has its state completely driven by React,
  • Uncontrolled components can maintain their own internal state. E.g., a textarea's value.
Source

[↑] Back to top

How would you prevent a component from rendering in React?

Return null from the render method.

Source

[↑] Back to top

How do you prevent the default behavior in an event callback in React?

You call e.preventDefault(); on the event e passed into the callback.

Source

[↑] Back to top

What is Key and benefit of using it in lists?

A key is a special string attribute you need to include when creating lists of elements. Keys help React identify which items have changed, are added, or are removed.

For example, most often we use IDs from your data as keys

const todoItems = todos.map((todo) =>
    <li key={todo.id}>
    {todo.text}
    </li>
);

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:

const todoItems = todos.map((todo, index) =>
    <li key={index}>
        {todo.text}
    </li>
);

Note:

  1. We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state
  2. If you extract list item as separate component then apply keys on list component instead li tag.

There will be a warning in the console if the key is not present on list items.

Source

[↑] Back to top

What's an alternative way to avoid having to bind to this in event callback methods?

Use arrow functions in your event handlers.

Source

[↑] Back to top

What is the point of using keys in React?

It allows for more efficient rendering of lists, so that React can reuse DOM elements without having to destroy + recreate them when lists change (slightly) in the UI.

Source

[↑] Back to top

What's the typical pattern for rendering a list of components from an array of data?

Call map on an array with an arrow function that executes for each array element, possibly outputting a React component for each.

Source

[↑] Back to top

What is the render method for?

To determine what should be rendered for a particular component. Could be a complex nested object of other child React components, or it could be as simple as a primitive JS object.

Source

[↑] Back to top

What is reconciliation in React?

It's React's process of re-rendering its tree of UI components.

Source

[↑] Back to top

What's the difference between an Element and a Component in React?

Elements are the fundamental building blocks of React, and describe what you want to see on the screen. They are just simple JS objects with props, key, ref, and type properties, whereas Components have a render method and optionally accept inputs.

Source

[↑] Back to top

What is the point of shouldComponentUpdate() method?

It's used for performance reasons, for example if the implementor of a component knows for sure that a particular property change does not necessitate a re-render, they could return false from this method and skip the re-render.

Source

[↑] Back to top

What are PropTypes in React?

They help indicate to React what data types a React component's properties are and should accept.

Source

[↑] Back to top

What's the difference between a "smart" component and a "dumb" component?

  • Smart components manage their state or in a Redux environment are connected to the Redux store.
  • Dumb components are driven completely by their props passed in from their parent and maintain no state of their own.
Source

[↑] Back to top

What is ReactDOM?

It's a top-level React API to render a React element into the DOM, via the ReactDOM.render method.

Source

[↑] Back to top

What are typical middleware choices for handling asynchronous calls in Redux?

  • Redux Thunk,
  • Redux Promise,
  • Redux Saga
Source

[↑] Back to top

What's the typical flow of data like in a React + Redux app?

Callback from UI component dispatches an action with a payload, which then is intercepted in a reducer, possibly producing a new application state, which is then propagated down through the tree of components in the application from the Redux store.

Source

[↑] Back to top

What is the difference between createElement and cloneElement?

  • createElement is what JSX gets transpiled to and is what React uses to create React Elements (object representations of some UI).
  • cloneElement is used in order to clone an element and pass it new props. They nailed the naming on these two.
Source

[↑] Back to top

Name the different lifecycle methods.

  • componentWillMount- this is most commonly used for App configuration in your root component.
  • componentDidMount - here you want to do all the setup you couldn’t do without a DOM, and start getting all the data you need. Also if you want to set up eventListeners etc. this lifecycle hook is a good place to do that.
  • componentWillReceiveProps - this lifecyclye acts on particular prop changes to trigger state transitions.
  • shouldComponentUpdate - if you’re worried about wasted renders shouldComponentUpdate is a great place to improve performance as it allows you to prevent a rerender if component receives new prop. shouldComponentUpdate should always return a boolean and based on what this is will determine if the component is rerendered or not.
  • componentWillUpdate - rarely used. It can be used instead of componentWillReceiveProps on a component that also has shouldComponentUpdate (but no access to previous props).
  • componentDidUpdate - also commonly used to update the DOM in response to prop or state changes.
  • componentWillUnmount - here you can cancel any outgoing network requests, or remove all event listeners associated with the component.
Source

[↑] Back to top

Given the code defined above, can you identify two problems?

Take a look at the code below:

class MyComponent extends React.Component {
  constructor(props) {
    // set the default internal state
    this.state = {
      clicks: 0
    };
  }

  componentDidMount() {
    this.refs.myComponentDiv.addEventListener('click', this.clickHandler);
  }

  componentWillUnmount() {
    this.refs.myComponentDiv.removeEventListener('click', this.clickHandler);
  }

  clickHandler() {
    this.setState({
      clicks: this.clicks + 1
    });
  }

  render() {
    let children = this.props.children;

    return (
      <div className="my-component" ref="myComponentDiv">
      <h2>My Component ({this.state.clicks} clicks})</h2>
      <h3>{this.props.headerText}</h3>
    {children}
    </div>
    );
  }
}

Given the code defined above, can you identify two problems?

Answer:

  1. The constructor does not pass its props to the super class. It should include the following line:
constructor(props) {
  super(props);
  // ...
}
  1. The event listener (when assigned via addEventListener()) is not properly scoped because ES2015 doesn’t provide autobinding. Therefore the developer can re-assign clickHandler in the constructor to include the correct binding to this:
constructor(props) {
  super(props);
  this.clickHandler = this.clickHandler.bind(this);
  // ...
}
Source

[↑] Back to top

What are stateless components?

Stateless components (a flavor of “reusable” components) are nothing more than pure functions that render DOM based solely on the properties provided to them.

const StatelessCmp = props => {
  return (
    <div className="my-stateless-component">
    {props.name}: {props.birthday}
    </div>
  );
};

// ---
ReactDOM.render(
  <StatelessCmp name="Art" birthday="10/01/1980" />,
  document.getElementById('main')
);

This component has no need for any internal state — let alone a constructor or lifecycle handlers. The output of the component is purely a function of the properties provided to it.

Source

[↑] Back to top

What are Pure Components?

PureComponent is exactly the same as Component except that it handles the shouldComponentUpdate method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component, on the other hand, won’t compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.

Source

[↑] Back to top

Name some popular Flux Libraries

While Flux is a general pattern for enforcing data flow through an application, there exist many implementations from which to choose from, for example:

  • Redux: perhaps the most popular Flux library today,
  • Alt.js: another popular library for managing data in React applications.
Source

[↑] Back to top

Why should not we update the state directly?

If you try to update state directly then it won’t re-render the component.

    //Wrong
    This.state.message =”Hello world”;

Instead use setState() method. It schedules an update to a component’s state object. When state changes, the component responds by re-rendering

    //Correct
    This.setState({message: ‘Hello World’});

Note: The only place you can assign the state is constructor.

Source

[↑] Back to top

What are controlled components?

In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state and update it based on user input. When a user submits a form the values from the aforementioned elements are sent with the form. With React it works differently. The component containing the form will keep track of the value of the input in it's state and will re-render the component each time the callback function e.g. onChange is fired as the state will be updated. An input form element whose value is controlled by React in this way is called a controlled component.

Source

[↑] Back to top

What is the difference between HTML and React event handling?

Below are the few differences between HTML and React event handling,

  1. In HTML, the event name should be in lowercase.
<button onclick="activateLasers()">

Whereas in ReactJS it follows camelCase convention,

<button onClick={activateLasers}>
  1. In HTML, you can return false to prevent default behavior,
<a href="#" onclick="console.log('The link was clicked.'); return false"/>
  1. Whereas in ReactJS you must call preventDefault explicitly,
function handleClick(e) {
      e.preventDefault();
      console.log('The link was clicked.');
}
Source

[↑] Back to top

How to bind methods or event handlers in JSX callbacks?

There are 3 possible ways to achieve,

  1. Binding in Constructor: In JavaScript classes, the methods are not bound by default. The same thing applies for ReactJS event handlers defined as class methods. Normally we bind them in constructor as follows,
constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
}

handleClick() {
    // Perform some logic
}
  1. Public class fields syntax: If you don’t like to use bind approach then public class fields syntax can be used to correctly bind callbacks
handleClick = () => {
     console.log('this is:', this);
}
<button onClick={this.handleClick}>
     Click me
</button>
  1. Arrow functions in callbacks: You can use arrow functions directly in the callbacks as below
<button onClick={(e) => this.handleClick(e)}>
      Click me
</button>
Source

[↑] Back to top

What can you tell me about JSX?

When Facebook first released React to the world, they also introduced a new dialect of JavaScript called JSX that embeds raw HTML templates inside JavaScript code. JSX code by itself cannot be read by the browser; it must be transpiled into traditional JavaScript using tools like Babel and webpack. While many developers understandably have initial knee-jerk reactions against it, JSX (in tandem with ES2015) has become the defacto method of defining React components.

class MyComponent extends React.Component {
  render() {
    let props = this.props;  
    return (
      <div className="my-component">
      <a href={props.url}>{props.name}</a>
      </div>
    );
  }
}
Source

[↑] Back to top

What are synthetic events in ReactJS?

SyntheticEvent is a cross-browser wrapper around the browser's native event. It's API is same as the browser's native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

Source

[↑] Back to top

What don't you like about React?

Source

[↑] Back to top

What are some limitations of things you shouldn't do in the component's render method?

You cannot modify the component's state (with setState), nor interact with the browser (do that in componentDidMount). Render should be a pure function.

Source

[↑] Back to top

What are forward refs?

Ref forwarding is a feature that lets some components take a ref they receive, and pass it further down to a child.

const ButtonElement = React.forwardRef((props, ref) => (
  <button ref={ref} className="CustomButton">
    {props.children}
  </button>
));

// Create ref to the DOM button:
const ref = React.createRef();
<ButtonElement ref={ref}>Forward Ref</ButtonElement>;
Source

[↑] Back to top

What is the difference between ShadowDOM and VirtualDOM?

The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.

Source

[↑] Back to top

What is an action?

Actions are plain javascript objects. They must have a type indicating the type of action being performed. In essence, actions are payloads of information that send data from your application to your store.

Source

[↑] Back to top

What are uncontrolled components?

The Uncontrolled Component are the one that stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML For example, in the below UserProfile component, the name input accessed using ref as below,

class UserProfile extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.input.current.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={this.input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

In most cases, it is recommend using controlled components to implement forms.

Source

[↑] Back to top

What is the difference between createElement and cloneElement?

JSX elements will be transpiled to createElement JS syntax to create React elements which are going to be used for the object representation of UI. Whereas cloneElement is used to clone an element and pass it to new props.

Source

[↑] Back to top

What is Lifting State Up in ReactJS?

When several components need to share the same changing data then it is recommended to lifting the shared state up to their closest common ancestor. For example, if two child components sharing the same data from its parent then move the state to parent instead of maintaining the local state inn both child components.

Source

[↑] Back to top

What are the different phases of ReactJS component lifecycle?

There are four different phases of React component’s lifecycle:

  1. Initialization: In this phase react component prepares setting up the initial state and default props.
  2. Mounting: The react component is ready to mount in the browser DOM. This phase covers componentWillMount and componentDidMount lifecycle methods.
  3. Updating: In this phase, the component get updated in two ways, sending the new props and updating the state. This phase covers shouldComponentUpdate, componentWillUpdate and componentDidUpdate lifecycle methods.
  4. Unmounting: In this last phase, the component is not needed and get unmounted from the browser DOM. This phase include componentWillUnmount lifecycle method.
Source

[↑] Back to top

What are the lifecycle methods of ReactJS?

  • componentWillMount: Executed before rendering and is used for App level configuration in your root component.
  • componentDidMount: Executed after first rendering and here all AJAX requests, DOM or state updates, and set up eventListeners should occur.
  • componentWillReceiveProps: Executed when particular prop updates to trigger state transitions.
  • shouldComponentUpdate: Determines if the component will be updated or not. By default it returns true. If you are sure that the component doesn't need to render after state or props are updated, you can return false value. It is a great place to improve performance as it allows you to prevent a rerender if component receives new prop.
  • componentWillUpdate: Executed before re-rendering the component when there are pros & state changes confirmed by shouldComponentUpdate which returns true.
  • componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes.
  • componentWillUnmount: It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.
Source

[↑] Back to top

What is a store in redux?

The store is a JavaScript object that holds application state. Along with this it also has the following responsibilities:

  • Allows access to state via getState();
  • Allows state to be updated via dispatch(action);
  • Registers listeners via subscribe(listener);
  • Handles unregistering of listeners via the function returned by subscribe(listener).
Source

[↑] Back to top

What is children prop?

Children is a prop (this.prop.children) that allow you to pass components as data to other components, just like any other prop you use.

There are a number of methods available in the React API to work with this prop. These include:

  • React.Children.map,
  • React.Children.forEach,
  • React.Children.count,
  • React.Children.only,
  • React.Children.toArray.

A simple usage of children prop looks as below,

var MyDiv = React.createClass({
  render: function() {
    return <div>{this.props.children}</div>;
  }
});

ReactDOM.render(
  <MyDiv>
    <span>Hello</span>
    <span>World</span>
  </MyDiv>,
  node
);
Source

[↑] Back to top

What is state in react?

State is similar to props, but it is private and fully controlled by the component. State is essentially an object that holds data and determines how the component renders and behaves.

Source

[↑] Back to top

What is equivalent of the following using React.createElement?

Question:

const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);

What is equivalent of the following using React.createElement?

Answer:

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);
Source

[↑] Back to top

How to set state with a dynamic key name?

If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with computed property names

handleInputChange : function (event) {
    this.setState({ [event.target.id]: event.target.value });
}
Source

[↑] Back to top

What would be the common mistake of function being called every time the component renders?

You need to make sure that function is not being called while passing the function as a parameter.

render() {
  // Wrong way: handleClick is called instead of passed as a reference!
  return <button onClick={this.handleClick()}>Click Me</button>
}

Instead, pass the function itself without parenthesis:

render() {
  // Correct way: handleClick is passed as a reference!
  return <button onClick={this.handleClick}>Click Me</button>
}
Source

[↑] Back to top

What is JSX?

JSX is a syntax extension to JavaScript and comes with the full power of JavaScript. JSX produces React elements. You can embed any JavaScript expression in JSX by wrapping it in curly braces. After compilation, JSX expressions become regular JavaScript objects. This means that you can use JSX inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions:

Source

[↑] Back to top

Why ReactJS uses className over class attribute?

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.

render() {
  return <span className="menu navigation-menu">Menu</span>
}
Source

[↑] Back to top

Why fragments are better than container divs?

Below are the reasons why fragments recommended

  1. Fragments bit faster and has less memory usage by without creating an extra DOM node. This only has a real benefit on very large and deep trees.
  2. Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationship, and adding divs in the middle makes it hard to keep the desired layout.
  3. The DOM inspector is less cluttered
Source

[↑] Back to top

What does "shouldComponentUpdate" do and why is it important?

What shouldComponentUpdate does is it’s a lifecycle method that allows us to opt out of setState reconciliation process for certain components (and their child components). If we know that a certain section of our UI isn’t going to change, there’s no reason to have React go through the trouble of trying to figure out if it should. By returning false from shouldComponentUpdate, React will assume that the current component, and all its child components, will stay the same as they currently are.

Source

[↑] Back to top

How would you prevent a component from rendering?

Returning null from a component's render method does not affect the firing of the component's lifecycle methods.

Source

[↑] Back to top

What is the alternative of binding this in the constructor?

You can use property initializers to correctly bind callbacks. This is enabled by default in create react app. You can use an arrow function in the callback. The problem here is that a new callback is created each time the component renders.

Source

[↑] Back to top

Why is it advised to pass a callback function to setState as opposed to an object?

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

Source

[↑] Back to top

What advantages are using arrow functions?

  • Scope safety: Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). An arrow function does not create its own this, the this value of the enclosing execution context is used.
  • Compactness: Arrow functions are easier to read and write.
  • Clarity: When almost everything is an arrow function, any regular function immediately sticks out for defining the scope. A developer can always look up the next-higher function statement to see what the thisObject is.
Source

[↑] Back to top

What are error boundaries in ReactJS (16)?

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info)

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

After that use it as a regular component

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>
Source

[↑] Back to top

What is a higher order component?

A higher-order component is a function that takes a component and returns a new component. HOC's allow you to reuse code, logic and bootstrap abstraction. The most common is probably Redux’s connect function. Beyond simply sharing utility libraries and simple composition, HOCs are the best way to share behavior between React Components. If you find yourself writing a lot of code in different places that does the same thing, you may be able to refactor that code into a reusable HOC.

Source

[↑] Back to top

What are the advantages of React over VueJS?

React has the following advantages over Vue:

  1. Gives more flexibility in large apps developing;
  2. Easier to test;
  3. Suitable for mobile apps creating;
  4. More information and solutions available
Source

[↑] Back to top

How do you tell React to build in Production mode and what will that do?

Typically you’d use Webpack’s DefinePlugin method to set NODE_ENV to production. This will strip out things like propType validation and extra warnings. On top of that, it’s also a good idea to minify your code because React uses Uglify’s dead-code elimination to strip out development only code and comments, which will drastically reduce the size of your bundle.

Source

[↑] Back to top

Describe Flux vs MVC?

Traditional MVC patterns have worked well for separating the concerns of data (Model), UI (View) and logic (Controller) — but MVC architectures frequently encounter two main problems:

  • Poorly defined data flow: The cascading updates which occur across views often lead to a tangled web of events which is difficult to debug.

  • Lack of data integrity: Model data can be mutated from anywhere, yielding unpredictable results across the UI.

With the Flux pattern complex UIs no longer suffer from cascading updates; any given React component will be able to reconstruct its state based on the data provided by the store. The Flux pattern also enforces data integrity by restricting direct access to the shared data.

Source

[↑] Back to top

Are you familiar with Flux?

Flux is an architectural pattern that enforces unidirectional data flow — its core purpose is to control derived data so that multiple components can interact with that data without risking pollution.

The Flux pattern is generic; it’s not specific to React applications, nor is it required to build a React app. However, Flux is commonly used by React developers because React components are declarative — the rendered UI (View) is simply a function of state (Store data).

react.js interview questions

In the Flux pattern, the Store is the central authority for all data; any mutations to the data must occur within the store. Changes to the Store data are subsequently broadcast to subscribing Views via events. Views then update themselves based on the new state of received data.

To request changes to any Store data, Actions may be fired. These Actions are controlled by a central Dispatcher; Actions may not occur simultaneously, ensuring that a Store only mutates data once per Action.

The strict unidirectional flow of this Flux pattern enforces data stability, reducing data-related runtime errors throughout an application.

Source

[↑] Back to top

What is the second argument that can optionally be passed to setState and what is its purpose?

A callback function which will be invoked when setState has finished and the component is re-rendered.

Something that’s not spoken of a lot is that setState is asynchronous, which is why it takes in a second callback function. Typically it’s best to use another lifecycle method rather than relying on this callback function, but it’s good to know it exists.

this.setState(
  { username: 'tylermcginnis33' },
  () => console.log('setState has finished and the component has re-rendered.')
)
Source

[↑] Back to top

What is wrong with this code?

Questions:

What is wrong with this code?

this.setState((prevState, props) => {
  return {
    streak: prevState.streak + props.count
  }
})

Answer:

Nothing is wrong with it. It’s rarely used and not well known, but you can also pass a function to setState that receives the previous state and props and returns a new state, just as we’re doing above. And not only is nothing wrong with it, but it’s also actively recommended if you’re setting state based on previous state.

Source

[↑] Back to top

How to create props proxy for HOC component?

You can add/edit props passed to the Component as a props proxy as below

function HOC(WrappedComponent) {
  return class Test extends Component {
    render() {
      const newProps = {
        title: 'New Header',
        footer: false,
        showFeatureX: false,
        showFeatureY: true
      };

      return <WrappedComponent {...this.props} {...newProps} />
    }
  }
}
Source

[↑] Back to top

Why would you eject from create-react-app?

Until you eject you are unable to configure webpack or babel presets.

Source

[↑] Back to top

What are some recent changes in the React library (e.g. in version 14, 15)?

  • Splitting out of ReactDOM into react-dom,
  • Introduction of refs,
  • Improved warnings + error messages...
Source

[↑] Back to top

What is mapStateToProps and mapDispatchToProps?

Functions typically seen in Redux applications that provide functions to Redux on how to map state / dispatch function to a set of props.

Source

[↑] Back to top

What is "Children"?

In JSX expressions that contain both an opening tag and a closing tag, the content between those tags is passed to components automatically as a special prop: props.children.

There are a number of methods available in the React API to work with this prop. These include:

  • React.Children.map
  • React.Children.forEach
  • React.Children.count
  • React.Children.only
  • React.Children.toArray
Source

[↑] Back to top

What's a pure functional component in React?

A component that has no internal state of its own, nor any side effects, and thus is often written as a function as opposed to an ES6 class.

Source

[↑] Back to top

Why does React use SyntheticEvents?

For consistent, cross-browser event handling (SyntheticEvent is a wrapper around the native browser event object).

Source

[↑] Back to top

Why would you use React.Children.map(props.children, () => ) instead of props.children.map(() => )?

Source

[↑] Back to top

What is the difference between a controlled component and an uncontrolled component?

  • A controlled component is a component where React is in control and is the single source of truth for the form data.
  • An uncontrolled component is where your form data is handled by the DOM, instead of inside your React component.

Though uncontrolled components are typically easier to implement since you just grab the value from the DOM using refs, it’s typically recommended that you favor controlled components over uncontrolled components. The main reasons for this are that controlled components support instant field validation, allow you to conditionally disable/enable buttons, enforce input formats, and are more “the React way”.

Source

[↑] Back to top

What is the difference between Flow and PropTypes?

  • Flow is a static analysis tool (static checker) which uses a superset of the language, allowing you to add type annotations to all of your code and catch an entire class of bugs at compile time.

  • PropTypes is a basic type checker (runtime checker) which has been patched onto React. It can't check anything other than the types of the props being passed to a given component. If you want more flexible typechecking for your entire project then Flow/TypeScript are appropriate choices.

Source

[↑] Back to top

What is the purpose of super(props)?

A child class constructor cannot make use of this until super() has been called. Also, ES2015 class constructors have to call super() if they are subclasses. The reason for passing props to super() is to enable you to access this.props in the constructor.

Source

[↑] Back to top

Why would you need to bind event handlers to "this"?

You need to do this in order for this to refer to the object instance of the React component class in your callback code, otherwise this will be undefined. An alternative is to use arrow functions in your event handlers and 'this' will be initialized as expected.

Source

[↑] Back to top

If you created a React element like Twitter below, what would the component definition of Twitter look like?

Question:

If you created a React element like Twitter below, what would the component definition of Twitter look like?

<Twitter username='tylermcginnis33'>
  {(user) => user === null
    ? <Loading />
    : <Badge info={user} />}
</Twitter>
import React, { Component, PropTypes } from 'react'
import fetchUser from 'twitter'
// fetchUser take in a username returns a promise
// which will resolve with that username's data.

class Twitter extends Component {
  // finish this
}

Answer:

Instead of another component as you’ve probably seen before, the Twitter component’s child is a function. What this means is that in the implementation of the Twitter component, we’ll need to treat props.children as a function.

import React, { Component, PropTypes } from 'react'
import fetchUser from 'twitter'

class Twitter extends Component {
  state = {
    user: null,
  }
  static propTypes = {
    username: PropTypes.string.isRequired,
  }
  componentDidMount () {
    fetchUser(this.props.username)
      .then((user) => this.setState({user}))
  }
  render () {
    return this.props.children(this.state.user)
  }
}

What’s great about this pattern is that we’ve decoupled our parent component from our child component. The parent component manages the state and the consumer of the parent component can decide in which way they’d like to apply the arguments they receive from the parent to their UI.

Source

[↑] Back to top

Which is preferred option with in callback refs and findDOMNode()?

It is preferred to use callback refs over findDOMNode() API because findDOMNode() prevents certain improvements in React in the future.

The legacy approach of using findDOMNode():

class MyComponent extends Component {
  componentDidMount() {
    findDOMNode(this).scrollIntoView();
  }

  render() {
    return <div />
  }
}

The recommended approach is

class MyComponent extends Component {
  componentDidMount() {
    this.node.scrollIntoView();
  }

  render() {
    return <div ref={node => this.node = node} />
  }
}
Source

[↑] Back to top

Why are String Refs legacy?

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like textInput, and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have below issues, are considered legacy, and are likely to be removed in one of the future releases.

  1. It requires that React keeps track of currently rendering component (since it can't guess this). This makes React a bit slower.
  2. It is not composable, i.e. if a library puts a ref on the passed child, the user can't put another ref on it. Callback refs are perfectly composable.
Source

[↑] Back to top

How to apply validation on Props in ReactJS?

When the application is running in development mode, React will automatically check for all props that we set on components to make sure they must right correct and right data type. For incorrect type, it will generate warning messages in the console for development mode whereas it is disabled in production mode due performance impact. The mandatory prop is defined with isRequired.

The set of predefined prop types are below

  1. React.PropTypes.string
  2. React.PropTypes.number
  3. React.PropTypes.func
  4. React.PropTypes.node
  5. React.PropTypes.bool

For example, we define propTypes for user component as below,

import PropTypes from 'prop-types';

class User extends React.Component {
  render() {
    return (
      <h1>Welcome, {this.props.name}</h1>
      <h2>Age, {this.props.age}
    );
  }
}

User.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired

};
Source

[↑] Back to top

What is a reducer?

A reducer is simply a pure function that takes the previous state and an action, and returns the next state.

Source

[↑] Back to top

Why would you use forceUpdate in a React component?

In order to force a re-render if there is some condition React is not detecting that requires an update to the UI. Typically this should not be necessary to call.

Source

[↑] Back to top

What is React Fiber?

Fiber is the new reconciliation engine or reimplementation core algorithm in React 16. Its main goal is to enable incremental rendering of the virtual DOM.The goal of React Fiber is to increase its suitability for areas like animation, layout, gestures, ability to pause, abort, or reuse work and assign priority to different types of updates; and new concurrency primitives.

The goal of React Fiber is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.

Source

[↑] Back to top

If you need to access the underlying DOM node for a React component, what's the typical way to do this in React?

ReactDOM.findDOMNode(component)
Source

[↑] Back to top

What are the recommended ways for static type checking?

Normally we use PropTypes library( React.PropTypes moved to a different package since React15.5) for TypeChecking in the ReactJS applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript to find out problems before run the code and provides auto-completion feature.

Source

[↑] Back to top

What is the difference between ReactJS and Angular?

ReactJS Angular
React is a Library and has only the View layer Angular is a Framework and has complete MVC functionality
React handle rendering on the server side Angular JS render on the client side but Angular 2 and above render on the server side
In React, HTML is written in JS which can be confusing Angular follows the template approach for HTML, which makes code shorter and easy to understand.
React native, which is a React type to build mobile applications are faster and more stable Ionic, Angular’s mobile native app is relatively less stable and slower
In React, data flows only in one way and hence debugging is easy In Angular, data flows both way i.e it has two-way data binding between children and parent and hence debugging is often difficult
Source

[↑] Back to top

What is the React context?

It's an experimental API that allows you to pass data down through a tree of components without having to use props.

Source

[↑] Back to top

Explain the Virtual DOM concept in React.

React builds up its own "virtual DOM" which is a lightweight representation of the DOM optimized for React's diffing algorithms and reconciliation process. Virtual DOM changes eventually propagate to the actual DOM at the end of the reconciliation process.

Source

[↑] Back to top

What is reselect and how it works?

Reselect is a selector library (for Redux) which uses memoization concept. It was originally written to compute derived data from redux-like applications state, but it can't be tied to any architecture or library.

Reselect keeps a copy of the last inputs/outputs of the last call, and recomputes the result only if one of the inputs changes. If the the same inputs are provided twice in a row, Reselect return the cached saved output. It's memoization and cache are fully customizable.

Source

[↑] Back to top

How to use Polymer in ReactJS?

Yes, it is possible. You need to follow below steps

  1. Create a polymer element.
<link rel="import" href="../../bower_components/polymer/polymer.html">
Polymer({
    is: 'calender-element',
    ready: function(){
        this.textContent = "I am a calender";
    }
});
  1. Make the polymer component a html tag by importing it in a html page. E.g. import it in the index.html of your react application
<link rel="import" href="./src/polymer-components/calender-element.html">
  1. Use that element in the jsx file.
'use strict';
import React from 'react';
class MyComponent extends React.Component{
    render(){
        return (
            <calender-element></calender-element>
        );
    }
}
export default MyComponent;
Source

[↑] Back to top

What is a pure function?

A Pure function is a function that doesn't depend on and doesn't modify the states of variables out of its scope. Essentially, this means that a pure function will always return the same result given same parameters.

Source

[↑] Back to top

Explain some difference between Flux and AngularJS (1.x) approach

UI components in AngularJS typically rely on some internal $scope to store their data. This data can be directly mutated from within the UI component or anything given access to $scope — a risky situation for any part of the component or greater application which relies on that data.

By contrast, the Flux pattern encourages the use of immutable data. Because the store is the central authority on all data, any mutations to that data must occur within the store. The risk of data pollution is greatly reduced.

Source

[↑] Back to top

What is React Fiber?

A rewrite under the covers of React to make it as responsive as possible, while maintaining backwards compatibility.

Source

[↑] Back to top

What is Redux Thunk used for?

Redux thunk is middleware that allows you to write action creators that return a function instead of an action. The thunk can then be used to delay the dispatch of an action if a certain condition is met. This allows you to handle the asyncronous dispatching of actions.

Source

[↑] Back to top