FrontendDeveloper.in

React Interview Questions

  • Question 181

    What are default props?

    The defaultProps can be defined as a property on the component to set the default values for the props. These default props are used when props not supplied(i.e., undefined props), but not for null or 0 as props. That means, If you provide null value then it remains null value. It's the same behavior with 0 as well.

    For example, let us create color default prop for the button component,

    function MyButton {
    // ...
    }
    
    MyButton.defaultProps = {
    color: "red",
    };
    

    If props.color is not provided then it will set the default value to 'red'. i.e, Whenever you try to access the color prop it uses the default value

    function MyButton() {
    return <MyButton />; // props.color will contain red value
    }
    
  • Question 182

    What is the purpose of displayName class property?

    The displayName string is used in debugging messages. Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component.

    For example, To ease debugging, choose a display name that communicates that it’s the result of a withSubscription HOC.

    function withSubscription(WrappedComponent) {
    class WithSubscription extends React.Component {
    /* ... */
    }
    WithSubscription.displayName = `WithSubscription(${getDisplayName(
    WrappedComponent
    )})`;
    return WithSubscription;
    }
    function getDisplayName(WrappedComponent) {
    return (
    WrappedComponent.displayName || WrappedComponent.name || "Component"
    );
    }
    
  • Question 183

    What is the browser support for react applications?

    React supports all popular browsers, including Internet Explorer 9 and above, although some polyfills are required for older browsers such as IE 9 and IE 10. If you use es5-shim and es5-sham polyfill then it even support old browsers that doesn't support ES5 methods.

  • Question 184

    What is code-splitting?

    Code-Splitting is a feature supported by bundlers like Webpack and Browserify which can create multiple bundles that can be dynamically loaded at runtime. The react project supports code splitting via dynamic import() feature.

    For example, in the below code snippets, it will make moduleA.js and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button.

    moduleA.js

    const moduleA = "Hello";
    
    export { moduleA };
    

    App.js

    export default function App {
    function handleClick() {
    import("./moduleA")
    .then(({ moduleA }) => {
    // Use moduleA
    })
    .catch((err) => {
    // Handle failure
    });
    };
    
     return (
    <button onClick={this.handleClick}>Load</button>
     );
    }
    

    See Class

    import React, { Component } from "react";
    
     class App extends Component {
    handleClick = () => {
    import("./moduleA")
    .then(({ moduleA }) => {
    // Use moduleA
    })
    .catch((err) => {
    // Handle failure
    });
    };
    
    render() {
    return (
    <button onClick={this.handleClick}>Load</button>
    );
    }
     }
    
     export default App;
    
  • Question 185

    What are Keyed Fragments?

    The Fragments declared with the explicit <React.Fragment> syntax may have keys. The general use case is mapping a collection to an array of fragments as below,

    function Glossary(props) {
    return (
    <dl>
    {props.items.map((item) => (
    // Without the `key`, React will fire a key warning
    <React.Fragment key={item.id}>
    <dt>{item.term}</dt>
    <dd>{item.description}</dd>
    </React.Fragment>
    ))}
    </dl>
    );
    }
    

    Note: key is the only attribute that can be passed to Fragment. In the future, there might be a support for additional attributes, such as event handlers.

  • Question 186

    Does React support all HTML attributes?

    As of React 16, both standard or custom DOM attributes are fully supported. Since React components often take both custom and DOM-related props, React uses the camelCase convention just like the DOM APIs.

    Let us take few props with respect to standard HTML attributes,

    <input readOnly={true} />  // Just like node.readOnly DOM API
    

    These props work similarly to the corresponding HTML attributes, with the exception of the special cases. It also support all SVG attributes.

  • Question 187

    When component props defaults to true?

    If you pass no value for a prop, it defaults to true. This behavior is available so that it matches the behavior of HTML.

    For example, below expressions are equivalent,

    <MyInput autocomplete />
    
    <MyInput autocomplete={true} />
    

    Note: It is not recommended to use this approach because it can be confused with the ES6 object shorthand (example, {name} which is short for {name: name})

  • Question 188

    What is NextJS and major features of it?

    Next.js is a popular and lightweight framework for static and server‑rendered applications built with React. It also provides styling and routing solutions. Below are the major features provided by NextJS,

    1. Server-rendered by default
    2. Automatic code splitting for faster page loads
    3. Simple client-side routing (page based)
    4. Webpack-based dev environment which supports (HMR)
    5. Able to implement with Express or any other Node.js HTTP server
    6. Customizable with your own Babel and Webpack configurations
  • Question 189

    How do you pass an event handler to a component?

    You can pass event handlers and other functions as props to child components. The functions can be passed to child component as below,

    function Button({ onClick }) {
    return <button onClick={onClick}>Download</button>;
    }
    
    export default function downloadExcel() {
    function handleClick() {
    alert("Downloaded");
    }
    
    return <Button onClick={handleClick}></Button>;
    }
    
  • Question 190

    How to prevent a function from being called multiple times?

    If you use an event handler such as onClick or onScroll and want to prevent the callback from being fired too quickly, then you can limit the rate at which callback is executed. This can be achieved in the below possible ways,

    1. Throttling: Changes based on a time based frequency. For example, it can be used using _.throttle lodash function
    2. Debouncing: Publish changes after a period of inactivity. For example, it can be used using _.debounce lodash function
    3. RequestAnimationFrame throttling: Changes based on requestAnimationFrame. For example, it can be used using raf-schd lodash function
  • Question 191

    How JSX prevents Injection Attacks?

    React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered.

    For example, you can embed user input as below,

    const name = response.potentiallyMaliciousInput;
    const element = <h1>{name}</h1>;
    

    This way you can prevent XSS(Cross-site-scripting) attacks in the application.

  • Question 192

    How do you update rendered elements?

    You can update UI(represented by rendered element) by passing the newly created element to ReactDOM's render method.

    For example, lets take a ticking clock example, where it updates the time by calling render method multiple times,

    function tick() {
    const element = (
    <h1>Hello, world!</h1>
    <h2>It is {new Date().toLocaleTimeString()}.</h2>
    );
    ReactDOM.render(element, document.getElementById("root"));
    }
    
    setInterval(tick, 1000);
    
  • Question 193

    How do you say that props are readonly?

    When you declare a component as a function or a class, it must never modify its own props.

    Let us take a below capital function,

    function capital(amount, interest) {
    return amount + interest;
    }
    

    The above function is called “pure” because it does not attempt to change their inputs, and always return the same result for the same inputs. Hence, React has a single rule saying "All React components must act like pure functions with respect to their props."

  • Question 194

    What are the conditions to safely use the index as a key?

    There are three conditions to make sure, it is safe use the index as a key.

    1. The list and items are static– they are not computed and do not change
    2. The items in the list have no ids
    3. The list is never reordered or filtered.
  • Question 195

    Should keys be globally unique?

    The keys used within arrays should be unique among their siblings but they don’t need to be globally unique. i.e, You can use the same keys with two different arrays.

    For example, the below Book component uses two arrays with different arrays,

    function Book(props) {
    const index = (
    <ul>
    {props.pages.map((page) => (
    <li key={page.id}>{page.title}</li>
    ))}
    </ul>
    );
    const content = props.pages.map((page) => (
    <h3>{page.title}</h3>
    ));
    return (
    {index}
    <hr />
    {content}
    );
    }
    
Get LinkedIn Premium at Rs 399