FrontendDeveloper.in

React Interview Questions

  • Question 166

    What is the purpose of registerServiceWorker in React?

    React creates a service worker for you without any configuration by default. The service worker is a web API that helps you cache your assets and other files so that when the user is offline or on a slow network, he/she can still see results on the screen, as such, it helps you build a better user experience, that's what you should know about service worker for now. It's all about adding offline capabilities to your site.

    import React from "react";
    import ReactDOM from "react-dom";
    import App from "./App";
    import registerServiceWorker from "./registerServiceWorker";
    
    ReactDOM.render(<App />, document.getElementById("root"));
    registerServiceWorker();
    
  • Question 167

    What is React memo function?

    Class components can be restricted from re-rendering when their input props are the same using PureComponent or shouldComponentUpdate. Now you can do the same with function components by wrapping them in React.memo.

    const MyComponent = React.memo(function MyComponent(props) {
    /* only rerenders if props change */
    });
    
  • Question 168

    What is React lazy function?

    The React.lazy function lets you render a dynamic import as a regular component. It will automatically load the bundle containing the OtherComponent when the component gets rendered. This must return a Promise which resolves to a module with a default export containing a React component.

    const OtherComponent = React.lazy(() => import("./OtherComponent"));
    
    function MyComponent() {
    return (
    <OtherComponent />
    );
    }
    

    Note: React.lazy and Suspense is not yet available for server-side rendering. If you want to do code-splitting in a server rendered app, we still recommend React Loadable.

  • Question 169

    How to prevent unnecessary updates using setState?

    You can compare the current value of the state with an existing state value and decide whether to rerender the page or not. If the values are the same then you need to return null to stop re-rendering otherwise return the latest state value.

    For example, the user profile information is conditionally rendered as follows,

    getUserProfile = (user) => {
    const latestAddress = user.address;
    this.setState((state) => {
    if (state.address === latestAddress) {
    return null;
    } else {
    return { title: latestAddress };
    }
    });
    };
    
  • Question 170

    How do you render Array, Strings and Numbers in React 16 Version?

    Arrays: Unlike older releases, you don't need to make sure render method return a single element in React16. You are able to return multiple sibling elements without a wrapping element by returning an array.

    For example, let us take the below list of developers,

    const ReactJSDevs = () => {
    return [
    <li key="1">John</li>,
    <li key="2">Jackie</li>,
    <li key="3">Jordan</li>,
    ];
    };
    

    You can also merge this array of items in another array component.

    const JSDevs = () => {
    return (
    <ul>
    <li>Brad</li>
    <li>Brodge</li>
    <ReactJSDevs />
    <li>Brandon</li>
    </ul>
    );
    };
    

    Strings and Numbers: You can also return string and number type from the render method.

    render() {
     return 'Welcome to ReactJS questions';
    }
    // Number
    render() {
     return 2018;
    }
    
  • Question 171

    What are hooks?

    Hooks is a special JavaScript function that allows you use state and other React features without writing a class. This pattern has been introduced as a new feature in React 16.8 and helped to isolate the stateful logic from the components.

    Let's see an example of useState hook:

    import { useState } from "react";
    
    function Example() {
    // Declare a new state variable, which we'll call "count"
    const [count, setCount] = useState(0);
    
    return (
    <>
    <button onClick={() => setCount(count + 1)}>Click me</button>
    </>
    );
    }
    

    Note: Hooks can be used inside an existing function component without rewriting the component.

  • Question 172

    What rules need to be followed for hooks?

    You need to follow two rules in order to use hooks,

    1. Call Hooks only at the top level of your react functions: You should always use hooks at the top level of react function before any early returns. i.e, You shouldn’t call Hooks inside loops, conditions, or nested functions. This will ensure that Hooks are called in the same order each time a component renders and it preserves the state of Hooks between multiple re-renders due to useState and useEffect calls.

    Let's see the difference using an example, Correct usage::

    function UserProfile() {
     // Correct: Hooks called at the top level
     const [name, setName] = useState('John');
     const [country, setCountry] = useState('US');
    
     return (
    <h1>Name: {name}</h1>
     );
    }
    

    Incorrect usage::

    function UserProfile() {
     const [name, setName] = useState('John');
    
     if (name === 'John') {
    // Incorrect: useState is called inside a conditional
    const [country, setCountry] = useState('US');
     }
    
     return (
    <h1>Name: {name}</h1>
     );
    }
    

    The useState hook for the country field is being called conditionally within an if block. This can lead to inconsistent state behavior and may cause hooks to be called in a different order on each re-render.

    1. Call Hooks from React Functions only: You shouldn’t call Hooks from regular JavaScript functions or class components. Instead, you should call them from either function components or custom hooks.

    Let's find the difference of correct and incorrect usage with below examples,

    Correct usage::

    //Example1:
    function Counter() {
     // Correct: useState is used inside a functional component
     const [count, setCount] = useState(0);
    
     return <div>Counter: {count}</div>;
    }
    //Example2:
    function useFetchData(url) {
     const [data, setData] = useState(null);
    
     useEffect(() => {
    fetch(url)
    .then((response) => response.json())
    .then((data) => setData(data));
     }, [url]);
    
     return data;
    }
    
    function UserProfile() {
     // Correct: Using a custom hook here
     const user = useFetchData('https://some-api.com/user');
    
     return (
    <h1>{user ? user.name : 'Loading profile...'}</h1>
     );
    }
    

    Incorrect usage::

    //Example1
    function normalFunction() {
    // Incorrect: Can't call hooks in normal functions
    const [count, setCount] = useState(0);
    }
    
    //Example2
    function fetchData(url) {
    // Incorrect: Hooks can't be used in non-React functions
    const [data, setData] = useState(null);
    
    useEffect(() => {
    fetch(url)
    .then((response) => response.json())
    .then((data) => setData(data));
    }, [url]);
    
    return data;
    }
    

    In the above incorrect usage example, both useState and useEffect are used in non-React functions(normalFunction and fetchData), which is not allowed.

  • Question 173

    How to ensure hooks followed the rules in your project?

    React team released an ESLint plugin called eslint-plugin-react-hooks that enforces Hook's two rules. It is part of Hooks API. You can add this plugin to your project using the below command,

    npm install eslint-plugin-react-hooks --save-dev
    

    And apply the below config in your ESLint config file,

    // Your ESLint configuration
    {
    "plugins": [
    // ...
    "react-hooks"
    ],
    "rules": {
    // ...
    "react-hooks/rules-of-hooks": "error"
    }
    }
    

    This plugin also provide another important rule through react-hooks/exhaustive-deps. It ensures that the dependencies of useEffect, useCallback, and useMemo hooks are correctly listed to avoid potential bugs.

    useEffect(() => {
    // Forgetting `message` will result in incorrect behavior
    console.log(message);
    }, []); // Here `message` should be a dependency
    

    The recommended eslint-config-react-app preset already includes the hooks rules of this plugin. For example, the linter enforce proper naming convention for hooks. If you rename your custom hooks which as prefix "use" to something else then linter won't allow you to call built-in hooks such as useState, useEffect etc inside of your custom hook anymore.

    Note: This plugin is intended to use in Create React App by default.

  • Question 174

    What are the differences between Flux and Redux?

    Below are the major differences between Flux and Redux

    FluxRedux
    State is mutableState is immutable
    The Store contains both state and change logicThe Store and change logic are separate
    There are multiple stores existThere is only one store exist
    All the stores are disconnected and flatSingle store with hierarchical reducers
    It has a singleton dispatcherThere is no concept of dispatcher
    React components subscribe to the storeContainer components uses connect function
  • Question 175

    What are the benefits of React Router V4?

    Below are the main benefits of React Router V4 module,

    1. In React Router v4(version 4), the API is completely about components. A router can be visualized as a single component(<BrowserRouter>) which wraps specific child router components(<Route>).
    2. You don't need to manually set history. The router module will take care history by wrapping routes with <BrowserRouter> component.
    3. The application size is reduced by adding only the specific router module(Web, core, or native)
  • Question 176

    Can you describe about componentDidCatch lifecycle method signature?

    The componentDidCatch lifecycle method is invoked after an error has been thrown by a descendant component. The method receives two parameters,

    1. error: - The error object which was thrown
    2. info: - An object with a componentStack key contains the information about which component threw the error.

    The method structure would be as follows

    componentDidCatch(error, info);
    
  • Question 177

    In which scenarios do error boundaries not catch errors?

    Below are the cases in which error boundaries don't work,

    1. Inside Event handlers
    2. Asynchronous code using setTimeout or requestAnimationFrame callbacks
    3. During Server side rendering
    4. When errors thrown in the error boundary code itself
  • Question 178

    What is the behavior of uncaught errors in react 16?

    In React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree. The reason behind this decision is that it is worse to leave corrupted UI in place than to completely remove it. For example, it is worse for a payments app to display a wrong amount than to render nothing.

  • Question 179

    What is the proper placement for error boundaries?

    The granularity of error boundaries usage is up to the developer based on project needs. You can follow either of these approaches,

    1. You can wrap top-level route components to display a generic error message for the entire application.
    2. You can also wrap individual components in an error boundary to protect them from crashing the rest of the application.
Get LinkedIn Premium at Rs 399