FrontendDeveloper.in

React Interview Questions

  • Question 76

    What are the exceptions on React component naming?

    The component names should start with an uppercase letter but there are few exceptions to this convention. The lowercase tag names with a dot (property accessors) are still considered as valid component names. For example, the below tag can be compiled to a valid component,

     render() {
    return (
    <obj.component/> // `React.createElement(obj.component)`
    )
    }
    
  • Question 77

    Is it possible to use async/await in plain React?

    Yes, you can use async/await in plain React, as long as your JavaScript environment supports ES2017+. Nowadays most modern browsers and build tools support ES2017+ version. If you're using Create React App, Next.js, Remix, or any modern React setup, async/await is supported out of the box through Babel.

  • Question 78

    Example Usage

    import { useEffect, useState } from 'react';
    
    function UserProfile() {
    const [user, setUser] = useState(null);
    
    useEffect(() => {
    const fetchUser = async () => {
    const response = await fetch('/api/user');
    const data = await response.json();
    setUser(data);
    };
    
    fetchUser();
    }, []);
    
    return user ? <div>Hello, {user.name}</div> : <div>Loading...</div>;
    }
    

    But If you're not using a bundler like Webpack or Babel, you will need Babel and transform-async-to-generator plugin. However, React Native ships with Babel and a set of transforms.

  • Question 79

    What are the common folder structures for React?

    There are two common practices for React project file structure.

    1. Grouping by features or routes:

    One common way to structure projects is locate CSS, JS, and tests together, grouped by feature or route.

    common/
    ├─ Avatar.js
    ├─ Avatar.css
    ├─ APIUtils.js
    └─ APIUtils.test.js
    feed/
    ├─ index.js
    ├─ Feed.js
    ├─ Feed.css
    ├─ FeedStory.js
    ├─ FeedStory.test.js
    └─ FeedAPI.js
    profile/
    ├─ index.js
    ├─ Profile.js
    ├─ ProfileHeader.js
    ├─ ProfileHeader.css
    └─ ProfileAPI.js
    
    1. Grouping by file type:

    Another popular way to structure projects is to group similar files together.

    api/
    ├─ APIUtils.js
    ├─ APIUtils.test.js
    ├─ ProfileAPI.js
    └─ UserAPI.js
    components/
    ├─ Avatar.js
    ├─ Avatar.css
    ├─ Feed.js
    ├─ Feed.css
    ├─ FeedStory.js
    ├─ FeedStory.test.js
    ├─ Profile.js
    ├─ ProfileHeader.js
    └─ ProfileHeader.css
    
  • Question 81

    What is the benefit of styles modules?

    It is recommended to avoid hard coding style values in components. Any values that are likely to be used across different UI components should be extracted into their own modules.

    For example, these styles could be extracted into a separate component:

    export const colors = {
    white,
    black,
    blue,
    };
    
    export const space = [0, 8, 16, 32, 64];
    

    And then imported individually in other components:

    import { space, colors } from "./styles";
    
  • Question 82

    What are the popular React-specific linters?

    ESLint is a popular JavaScript linter. There are plugins available that analyse specific code styles. One of the most common for React is an npm package called eslint-plugin-react. By default, it will check a number of best practices, with rules checking things from keys in iterators to a complete set of prop types.

    Another popular plugin is eslint-plugin-jsx-a11y, which will help fix common issues with accessibility. As JSX offers slightly different syntax to regular HTML, issues with alt text and tabindex, for example, will not be picked up by regular plugins.

    React Router

  • Question 83

    What is React Router?

    React Router is a powerful routing library built on top of React that helps you add new screens and flows to your application incredibly quickly, all while keeping the URL in sync with what's being displayed on the page.

  • Question 84

    How React Router is different from history library?

    React Router is a wrapper around the history library which handles interaction with the browser's window.history with its browser and hash histories. It also provides memory history which is useful for environments that don't have global history, such as mobile app development (React Native) and unit testing with Node.

  • Question 85

    What are the `<Router>` components of React Router v6?

    React Router v6 provides below 4 <Router> components:

    1. <BrowserRouter>:Uses the HTML5 history API for standard web apps.
    2. <HashRouter>:Uses hash-based routing for static servers.
    3. <MemoryRouter>:Uses in-memory routing for testing and non-browser environments.
    4. <StaticRouter>:Provides static routing for server-side rendering (SSR).

    The above components will create browser, hash, memory and static history instances. React Router v6 makes the properties and methods of the history instance associated with your router available through the context in the router object.

  • Question 87

    How do you programmatically navigate using React Router v4?

    There are three different ways to achieve programmatic routing/navigation within components.

    1. Using the withRouter() higher-order function:

    The withRouter() higher-order function will inject the history object as a prop of the component. This object provides push() and replace() methods to avoid the usage of context.

    import { withRouter } from "react-router-dom"; // this also works with 'react-router-native'
    
    const Button = withRouter(({ history }) => (
    <button
    type="button"
    onClick={() => {
    history.push("/new-location");
    }}
    >
    {"Click Me!"}
    </button>
    ));
    
    1. Using <Route> component and render props pattern:

    The <Route> component passes the same props as withRouter(), so you will be able to access the history methods through the history prop.

    import { Route } from "react-router-dom";
    
    const Button = () => (
    <Route
    render={({ history }) => (
    <button
    type="button"
    onClick={() => {
    history.push("/new-location");
    }}
    >
    {"Click Me!"}
    </button>
    )}
    />
    );
    
    1. Using context:

    This option is not recommended and treated as unstable API.

    const Button = (props, context) => (
    <button
    type="button"
    onClick={() => {
    context.history.push("/new-location");
    }}
    >
    {"Click Me!"}
    </button>
    );
    
    Button.contextTypes = {
    history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired,
    }),
    };
    
  • Question 88

    How to get query parameters in React Router v4?

    The ability to parse query strings was taken out of React Router v4 because there have been user requests over the years to support different implementation. So the decision has been given to users to choose the implementation they like. The recommended approach is to use query strings library.

    const queryString = require("query-string");
    const parsed = queryString.parse(props.location.search);
    

    You can also use URLSearchParams if you want something native:

    const params = new URLSearchParams(props.location.search);
    const foo = params.get("name");
    

    You should use a polyfill for IE11.

  • Question 89

    Why you get "Router may have only one child element" warning?

    You have to wrap your Route's in a <Switch> block because <Switch> is unique in that it renders a route exclusively.

    At first you need to add Switch to your imports:

    import { Switch, Router, Route } from "react-router";
    

    Then define the routes within <Switch> block:

    <Router>
    <Switch>
    <Route {/* ... */} />
    <Route {/* ... */} />
    </Switch>
    </Router>
    
Get LinkedIn Premium at Rs 399