FrontendDeveloper.in

React Interview Questions

  • Question 376

    What are render props?

    Render Props is a simple technique for sharing code between components using a prop whose value is a function. The below component uses render prop which returns a React element.

    <DataProvider render={(data) => <h1>{`Hello ${data.target}`}</h1>} />
    

    Libraries such as React Router and DownShift are using this pattern.

  • Question 377

    How to dispatch an action on load?

    You can dispatch an action in componentDidMount() method and in render() method you can verify the data.

    class App extends Component {
    componentDidMount() {
    this.props.fetchData();
    }
    
    render() {
    return this.props.isLoaded ? (
    ) : (
    );
    }
    }
    
    const mapStateToProps = (state) => ({
    isLoaded: state.isLoaded,
    });
    
    const mapDispatchToProps = { fetchData };
    
    export default connect(mapStateToProps, mapDispatchToProps)(App);
    
  • Question 378

    How to use `connect()` from React Redux?

    You need to follow two steps to use your store in your container:

    1. Use mapStateToProps(): It maps the state variables from your store to the props that you specify.
    2. Connect the above props to your container: The object returned by the mapStateToProps function is connected to the container. You can import connect() from react-redux.
    import React from "react";
    import { connect } from "react-redux";
    
    class App extends React.Component {
    render() {
    return <div>{this.props.containerData}</div>;
    }
    }
    
    function mapStateToProps(state) {
    return { containerData: state.data };
    }
    
    export default connect(mapStateToProps)(App);
    
  • Question 379

    Whats the purpose of `at` symbol in the Redux connect decorator?

    The @ symbol is in fact a JavaScript expression used to signify decorators. Decorators make it possible to annotate and modify classes and properties at design time.

    Let's take an example setting up Redux without and with a decorator.

    • Without decorator:
    import React from "react";
    import * as actionCreators from "./actionCreators";
    import { bindActionCreators } from "redux";
    import { connect } from "react-redux";
    
    function mapStateToProps(state) {
    return { todos: state.todos };
    }
    
    function mapDispatchToProps(dispatch) {
    return { actions: bindActionCreators(actionCreators, dispatch) };
    }
    
    class MyApp extends React.Component {
    // ...define your main app here
    }
    
    export default connect(mapStateToProps, mapDispatchToProps)(MyApp);
    
    • With decorator:
    import React from "react";
    import * as actionCreators from "./actionCreators";
    import { bindActionCreators } from "redux";
    import { connect } from "react-redux";
    
    function mapStateToProps(state) {
    return { todos: state.todos };
    }
    
    function mapDispatchToProps(dispatch) {
    return { actions: bindActionCreators(actionCreators, dispatch) };
    }
    
    @connect(mapStateToProps, mapDispatchToProps)
    export default class MyApp extends React.Component {
    // ...define your main app here
    }
    

    The above examples are almost similar except the usage of decorator. The decorator syntax isn't built into any JavaScript runtimes yet, and is still experimental and subject to change. You can use babel for the decorators support.

  • Question 380

    How to use TypeScript in `create-react-app` application?

    Starting from react-scripts@3.3.0+ releases onwards, you can now optionally start a new app from a template by appending --template [template-name] to the creation command. If you don't select a template, it will create your project with base template. Remember that templates are always named in the format cra-template-[template-name], here you only need to fill the [template-name] section.

    The typeScript can be used in your project by appending --template typescript to the creation command.

    npx create-react-app my-app --template typescript
    

    But if you are using React Scripting between react-scripts@2.1.0 and react-scripts@3.2.x , there is a built-in support for TypeScript. i.e, create-react-app now supports TypeScript natively. You can just pass --typescript option as below

    npx create-react-app my-app --typescript
    
    # or
    
    yarn create react-app my-app --typescript
    

    Whereas for lower versions of react scripts, just supply --scripts-version option as react-scripts-ts while you create a new project. react-scripts-ts is a set of adjustments to take the standard create-react-app project pipeline and bring TypeScript into the mix.

    Now the project layout should look like the following:

    my-app/
    ├─ .gitignore
    ├─ images.d.ts
    ├─ node_modules/
    ├─ public/
    ├─ src/
    │  └─ ...
    ├─ package.json
    ├─ tsconfig.json
    ├─ tsconfig.prod.json
    ├─ tsconfig.test.json
    └─ tslint.json
    
  • Question 381

    Does the statics object work with ES6 classes in React?

    No, statics only works with React.createClass():

    someComponent = React.createClass({
    statics: {
    someMethod: function () {
    // ..
    },
    },
    });
    

    But you can write statics inside ES6+ classes as below,

    class Component extends React.Component {
    static propTypes = {
    // ...
    };
    
    static someMethod() {
    // ...
    }
    }
    

    or writing them outside class as below,

    class Component extends React.Component {
    ....
    }
    
    Component.propTypes = {...}
    Component.someMethod = function(){....}
    
  • Question 382

    Why are inline ref callbacks or functions not recommended?

    If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one.

    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>
    );
    }
    }
    

    But our expectation is for the ref callback to get called once, when the component mounts. One quick fix is to use the ES7 class property syntax to define the function

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

    What are HOC factory implementations?

    There are two main ways of implementing HOCs in React.

    1. Props Proxy (PP) and
    2. Inheritance Inversion (II).

    But they follow different approaches for manipulating the WrappedComponent.

    Props Proxy

    In this approach, the render method of the HOC returns a React Element of the type of the WrappedComponent. We also pass through the props that the HOC receives, hence the name Props Proxy.

    function ppHOC(WrappedComponent) {
    return class PP extends React.Component {
    render() {
    return <WrappedComponent {...this.props} />;
    }
    };
    }
    

    Inheritance Inversion

    In this approach, the returned HOC class (Enhancer) extends the WrappedComponent. It is called Inheritance Inversion because instead of the WrappedComponent extending some Enhancer class, it is passively extended by the Enhancer. In this way the relationship between them seems inverse.

    function iiHOC(WrappedComponent) {
    return class Enhancer extends WrappedComponent {
    render() {
    return super.render();
    }
    };
    }
    
  • Question 384

    How to use class field declarations syntax in React classes?

    React Class Components can be made much more concise using the class field declarations. You can initialize the local state without using the constructor and declare class methods by using arrow functions without the extra need to bind them.

    Let's take a counter example to demonstrate class field declarations for state without using constructor and methods without binding,

    class Counter extends Component {
    state = { value: 0 };
    
    handleIncrement = () => {
    this.setState((prevState) => ({
    value: prevState.value + 1,
    }));
    };
    
    handleDecrement = () => {
    this.setState((prevState) => ({
    value: prevState.value - 1,
    }));
    };
    
    render() {
    return (
    {this.state.value}
    
    <button onClick={this.handleIncrement}>+</button>
    <button onClick={this.handleDecrement}>-</button>
    );
    }
    }
    
  • Question 385

    Why do you not need error boundaries for event handlers?

    Error boundaries do not catch errors inside event handlers.

    React doesn’t need error boundaries to recover from errors in event handlers. Unlike the render method and lifecycle methods, the event handlers don’t happen during rendering. So if they throw, React still knows what to display on the screen.

    If you need to catch an error inside an event handler, use the regular JavaScript try / catch statement:

    class MyComponent extends React.Component {
    constructor(props) {
    super(props);
    this.state = { error: null };
    this.handleClick = this.handleClick.bind(this);
    }
    
    handleClick() {
    try {
    // Do something that could throw
    } catch (error) {
    this.setState({ error });
    }
    }
    
    render() {
    if (this.state.error) {
    return <h1>Caught an error.</h1>;
    }
    return <button onClick={this.handleClick}>Click Me</button>;
    }
    }
    

    Note that the above example is demonstrating regular JavaScript behavior and doesn’t use error boundaries.

  • Question 386

    What is the difference between try catch block and error boundaries?

    Try catch block works with imperative code whereas error boundaries are meant for declarative code to render on the screen.

    For example, the try catch block used for below imperative code

    try {
    showButton();
    } catch (error) {
    // ...
    }
    

    Whereas error boundaries wrap declarative code as below,

    <ErrorBoundary>
    <MyComponent />
    </ErrorBoundary>
    

    So if an error occurs in a componentDidUpdate method caused by a setState somewhere deep in the tree, it will still correctly propagate to the closest error boundary.

  • Question 388

    What are the possible return types of render method?

    Below are the list of following types used and return from render method,

    1. React elements: Elements that instruct React to render a DOM node. It includes html elements such as <div/> and user defined elements.
    2. Arrays and fragments: Return multiple elements to render as Arrays and Fragments to wrap multiple elements
    3. Portals: Render children into a different DOM subtree.
    4. String and numbers: Render both Strings and Numbers as text nodes in the DOM
    5. Booleans or null: Doesn't render anything but these types are used to conditionally render content.
  • Question 389

    What is the main purpose of constructor?

    The constructor is mainly used for two purposes,

    1. To initialize local state by assigning object to this.state
    2. For binding event handler methods to the instance For example, the below code covers both the above cases,
    constructor(props) {
    super(props);
    // Don't call this.setState() here!
    this.state = { counter: 0 };
    this.handleClick = this.handleClick.bind(this);
    }
    
Get LinkedIn Premium at Rs 399