FrontendDeveloper.in

React Interview Questions

  • Question 406

    What is the purpose of forward ref in HOCs?

    Refs will not get passed through because ref is not a prop. It is handled differently by React just like key. If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component. In this case, you can use Forward Ref API. For example, we can explicitly forward refs to the inner FancyButton component using the React.forwardRef API.

    The below HOC logs all props,

    function logProps(Component) {
    class LogProps extends React.Component {
    componentDidUpdate(prevProps) {
    console.log("old props:", prevProps);
    console.log("new props:", this.props);
    }
    
    render() {
    const { forwardedRef, ...rest } = this.props;
    
    // Assign the custom prop "forwardedRef" as a ref
    return <Component ref={forwardedRef} {...rest} />;
    }
    }
    
    return React.forwardRef((props, ref) => {
    return <LogProps {...props} forwardedRef={ref} />;
    });
    }
    

    Let's use this HOC to log all props that get passed to our “fancy button” component,

    class FancyButton extends React.Component {
    focus() {
    // ...
    }
    
    // ...
    }
    export default logProps(FancyButton);
    

    Now let's create a ref and pass it to FancyButton component. In this case, you can set focus to button element.

    import FancyButton from "./FancyButton";
    
    const ref = React.createRef();
    ref.current.focus();
    <FancyButton label="Click Me" handleClick={handleClick} ref={ref} />;
    
  • Question 408

    Why do you need additional care for component libraries while using forward refs?

    When you start using forwardRef in a component library, you should treat it as a breaking change and release a new major version of your library. This is because your library likely has a different behavior such as what refs get assigned to, and what types are exported. These changes can break apps and other libraries that depend on the old behavior.

  • Question 409

    How to create react class components without ES6?

    If you don’t use ES6 then you may need to use the create-react-class module instead. For default props, you need to define getDefaultProps() as a function on the passed object. Whereas for initial state, you have to provide a separate getInitialState method that returns the initial state.

    var Greeting = createReactClass({
    getDefaultProps: function () {
    return {
    name: "Jhohn",
    };
    },
    getInitialState: function () {
    return { message: this.props.message };
    },
    handleClick: function () {
    console.log(this.state.message);
    },
    render: function () {
    return <h1>Hello, {this.props.name}</h1>;
    },
    });
    

    Note: If you use createReactClass then auto binding is available for all methods. i.e, You don't need to use .bind(this) with in constructor for event handlers.

  • Question 410

    Is it possible to use react without JSX?

    Yes, JSX is not mandatory for using React. Actually it is convenient when you don’t want to set up compilation in your build environment. Each JSX element is just syntactic sugar for calling React.createElement(component, props, ...children).

    For example, let us take a greeting example with JSX,

    class Greeting extends React.Component {
    render() {
    return <div>Hello {this.props.message}</div>;
    }
    }
    
    ReactDOM.render(
    <Greeting message="World" />,
    document.getElementById("root")
    );
    

    You can write the same code without JSX as below,

    class Greeting extends React.Component {
    render() {
    return React.createElement("div", null, `Hello ${this.props.message}`);
    }
    }
    
    ReactDOM.render(
    React.createElement(Greeting, { message: "World" }, null),
    document.getElementById("root")
    );
    
  • Question 411

    How do you create HOC using render props?

    You can implement most higher-order components (HOC) using a regular component with a render prop. For example, if you would prefer to have a withMouse HOC instead of a <Mouse> component, you could easily create one using a regular <Mouse> with a render prop.

    function withMouse(Component) {
    return class extends React.Component {
    render() {
    return (
    <Mouse
    render={(mouse) => <Component {...this.props} mouse={mouse} />}
    />
    );
    }
    };
    }
    

    This way render props gives the flexibility of using either pattern.

  • Question 412

    What is react scripts?

    The react-scripts package is a set of scripts from the create-react-app starter pack which helps you kick off projects without configuring. The react-scripts start command sets up the development environment and starts a server, as well as hot module reloading.

  • Question 413

    What are the features of create react app?

    Below are the list of some of the features provided by create react app.

    1. React, JSX, ES6, Typescript and Flow syntax support.
    2. Autoprefixed CSS
    3. CSS Reset/Normalize
    4. A live development server
    5. A fast interactive unit test runner with built-in support for coverage reporting
    6. A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps
    7. An offline-first service worker and a web app manifest, meeting all the Progressive Web App criteria.
  • Question 414

    What is the purpose of renderToNodeStream method?

    The ReactDOMServer#renderToNodeStream method is used to generate HTML on the server and send the markup down on the initial request for faster page loads. It also helps search engines to crawl your pages easily for SEO purposes. Note: Remember this method is not available in the browser but only server.

  • Question 415

    How do you get redux scaffolding using create-react-app?

    Redux team has provided official redux+js or redux+typescript templates for create-react-app project. The generated project setup includes,

    1. Redux Toolkit and React-Redux dependencies
    2. Create and configure Redux store
    3. React-Redux <Provider> passing the store to React components
    4. Small "counter" example to demo how to add redux logic and React-Redux hooks API to interact with the store from components The below commands need to be executed along with template option as below,
    5. Javascript template:
    npx create-react-app my-app --template redux
    
    1. Typescript template:
    npx create-react-app my-app --template redux-typescript
    
  • Question 416

    What is state mutation and how to prevent it?

    State mutation happens when you try to update the state of a component without actually using setState function. This can happen when you are trying to do some computations using a state variable and unknowingly save the result in the same state variable. This is the main reason why it is advised to return new instances of state variables from the reducers by using Object.assign({}, ...) or spread syntax.

    This can cause unknown issues in the UI as the value of the state variable got updated without telling React to check what all components were being affected from this update and it can cause UI bugs.

    Ex:

    class A extends React.component {
    constructor(props) {
    super(props);
    this.state = {
    loading: false
    }
     }
    
    componentDidMount() {
    let { loading } = this.state;
    loading = (() => true)(); // Trying to perform an operation and directly saving in a state variable
    }
    
    

    How to prevent it: Make sure your state variables are immutable by either enforcing immutability by using plugins like Immutable.js, always using setState to make updates, and returning new instances in reducers when sending updated state values.

Get LinkedIn Premium at Rs 399