FrontendDeveloper.in

React Interview Questions

  • Question 46

    How to use styles in React?

    The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes.

    const divStyle = {
    color: "blue",
    backgroundImage: "url(" + imgUrl + ")",
    };
    
    function HelloWorldComponent() {
    return <div style={divStyle}>Hello World!</div>;
    }
    

    Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes in JavaScript (e.g. node.style.backgroundImage).

  • Question 47

    How events are different in React?

    Handling events in React elements has some syntactic differences:

    1. React event handlers are named using camelCase, rather than lowercase.
    2. With JSX you pass a function as the event handler, rather than a string.
  • Question 48

    What is the impact of indexes as keys?

    Keys should be stable, predictable, and unique so that React can keep track of elements.

    In the below code snippet each element's key will be based on ordering, rather than tied to the data that is being represented. This limits the optimizations that React can do and creates confusing bugs in the application.

    {
    todos.map((todo, index) => <Todo {...todo} key={index} />);
    }
    

    If you use element data for unique key, assuming todo.id is unique to this list and stable, React would be able to reorder elements without needing to reevaluate them as much.

    {
    todos.map((todo) => <Todo {...todo} key={todo.id} />);
    }
    

    Note: If you don't specify key prop at all, React will use index as a key's value while iterating over an array of data.

  • Question 49

    How do you conditionally render components?

    In some cases you want to render different components depending on some state. JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true.

    const MyComponent = ({ name, address }) => (
    <h2>{name}</h2>
    {address && <p>{address}</p>}
    );
    

    If you need an if-else condition then use ternary operator.

    const MyComponent = ({ name, address }) => (
    <h2>{name}</h2>
    {address ? <p>{address}</p> : <p>{"Address is not available"}</p>}
    );
    
  • Question 50

    Why we need to be careful when spreading props on DOM elements?

    When we spread props we run into the risk of adding unknown HTML attributes, which is a bad practice. Instead we can use prop destructuring with ...rest operator, so it will add only required props.

    For example,

    const ComponentA = () => (
    <ComponentB isDisplay={true} className={"componentStyle"} />
    );
    
    const ComponentB = ({ isDisplay, ...domProps }) => (
    );
    
  • Question 51

    How do you memoize a component?

    There are memoize libraries available which can be used on function components.

    For example moize library can memoize the component in another component.

    import moize from "moize";
    import Component from "./components/Component"; // this module exports a non-memoized component
    
    const MemoizedFoo = moize.react(Component);
    
    const Consumer = () => {
    {"I will memoize the following entry:"}
    <MemoizedFoo />
    };
    

    Update: Since React v16.6.0, we have a React.memo. It provides a higher order component which memoizes component unless the props change. To use it, simply wrap the component using React.memo before you use it.

    const MemoComponent = React.memo(function MemoComponent(props) {
    /* render using props */
    });
    OR;
    export default React.memo(MyFunctionComponent);
    
  • Question 52

    How you implement Server Side Rendering or SSR?

    React is already equipped to handle rendering on Node servers. A special version of the DOM renderer is available, which follows the same pattern as on the client side.

    import ReactDOMServer from "react-dom/server";
    import App from "./App";
    
    ReactDOMServer.renderToString(<App />);
    

    This method will output the regular HTML as a string, which can be then placed inside a page body as part of the server response. On the client side, React detects the pre-rendered content and seamlessly picks up where it left off.

  • Question 53

    How to enable production mode in React?

    You should use Webpack's DefinePlugin method to set NODE_ENV to production, by which it strip out things like propType validation and extra warnings. Apart from this, if you minify the code, for example, Uglify's dead-code elimination to strip out development only code and comments, it will drastically reduce the size of your bundle.

  • Question 55

    What is a switching component?

    A switching component is a component that renders one of many components. We need to use object to map prop values to components.

    For example, a switching component to display different pages based on page prop:

    import HomePage from "./HomePage";
    import AboutPage from "./AboutPage";
    import ServicesPage from "./ServicesPage";
    import ContactPage from "./ContactPage";
    
    const PAGES = {
    home: HomePage,
    about: AboutPage,
    services: ServicesPage,
    contact: ContactPage,
    };
    
    const Page = (props) => {
    const Handler = PAGES[props.page] || ContactPage;
    
    return <Handler {...props} />;
    };
    
    // The keys of the PAGES object can be used in the prop types to catch dev-time errors.
    Page.propTypes = {
    page: PropTypes.oneOf(Object.keys(PAGES)).isRequired,
    };
    
  • Question 56

    What are React Mixins?

    Mixins are a way to totally separate components to have a common functionality. Mixins should not be used and can be replaced with higher-order components or decorators.

    One of the most commonly used mixins is PureRenderMixin. You might be using it in some components to prevent unnecessary re-renders when the props and state are shallowly equal to the previous props and state:

    const PureRenderMixin = require("react-addons-pure-render-mixin");
    
    const Button = React.createClass({
    mixins: [PureRenderMixin],
    // ...
    });
    
    <!-- TODO: mixins are deprecated -->
  • Question 57

    What are the Pointer Events supported in React?

    Pointer Events provide a unified way of handling all input events. In the old days we had a mouse and respective event listeners to handle them but nowadays we have many devices which don't correlate to having a mouse, like phones with touch surface or pens. We need to remember that these events will only work in browsers that support the Pointer Events specification.

    The following event types are now available in React DOM:

    1. onPointerDown
    2. onPointerMove
    3. onPointerUp
    4. onPointerCancel
    5. onGotPointerCapture
    6. onLostPointerCapture
    7. onPointerEnter
    8. onPointerLeave
    9. onPointerOver
    10. onPointerOut
  • Question 58

    Why should component names start with capital letter?

    If you are rendering your component using JSX, the name of that component has to begin with a capital letter otherwise React will throw an error as an unrecognized tag. This convention is because only HTML elements and SVG tags can begin with a lowercase letter.

    function SomeComponent {
    // Code goes here
    }
    

    You can define function component whose name starts with lowercase letter, but when it's imported it should have a capital letter. Here lowercase is fine:

    function myComponent {
    render() {
    return <div />;
    }
    }
    
    export default myComponent;
    

    While when imported in another file it should start with capital letter:

    import MyComponent from "./myComponent";
    
  • Question 59

    Are custom DOM attributes supported in React v16?

    Yes. In the past, React used to ignore unknown DOM attributes. If you wrote JSX with an attribute that React doesn't recognize, React would just skip it.

    For example, let's take a look at the below attribute:

    Would render an empty div to the DOM with React v15:

    In React v16 any unknown attributes will end up in the DOM:

    This is useful for supplying browser-specific non-standard attributes, trying new DOM APIs, and integrating with opinionated third-party libraries.

  • Question 60

    How to loop inside JSX?

    You can simply use Array.prototype.map with ES6 arrow function syntax.

    For example, the items array of objects is mapped into an array of components:

    <tbody>
    {items.map((item) => (
    <SomeComponent key={item.id} name={item.name} />
    ))}
    </tbody>
    

    But you can't iterate using for loop:

    <tbody>
    for (let i = 0; i < items.length; i++) {
    <SomeComponent key={items[i].id} name={items[i].name} />
    }
    </tbody>
    

    This is because JSX tags are transpiled into function calls, and you can't use statements inside expressions. This may change thanks to do expressions which are stage 1 proposal.

Get LinkedIn Premium at Rs 399