React Native and Ecosystem Interview Questions

Table of Contents +

React interviews often expand into the broader ecosystem, not just the core library. This section covers React Native, ecosystem libraries, framework comparisons, tooling, forms libraries, and related React platform questions.

This page includes 48 questions in this topic group.

How do you import and export components using React and ES6?

You should use default for exporting the components

import User from "user";
export default function MyProfile {
return <User type="customer">//...</User>;
}

Class-based version

import React from "react";
import User from "user";
export default class MyProfile extends React.Component {
render() {
return <User type="customer">//...</User>;
}
}

With the export specifier, the MyProfile is going to be the member and exported to this module and the same can be imported without mentioning the name in other components.

## 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,
```jsx
render() {
return (
<obj.component/> // `React.createElement(obj.component)`
)
}

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.

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.

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

React Transition Group and React Motion are popular animation packages in React ecosystem.

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";

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

What is the difference between React Native and React?

React is a JavaScript library, supporting both front end web and being run on the server, for building user interfaces and web applications.

React Native is a mobile framework that compiles to native app components, allowing you to build native mobile applications (iOS, Android, and Windows) in JavaScript that allows you to use React to build your components, and implements React under the hood.

How do you test React Native apps?

React Native can be tested only in mobile simulators like iOS and Android. You can run the app in your mobile using expo app (https://expo.io) Where it syncs using QR code, your mobile and computer should be in same wireless network.

How do you do logging in React Native?

You can use console.log, console.warn, etc. As of React Native v0.29 you can simply run the following to see logs in the console:

$ react-native log-ios
$ react-native log-android

How do you debug your React Native?

Follow the below steps to debug React Native app:

  1. Run your application in the iOS simulator.
  2. Press Command + D and a webpage should open up at http://localhost:8081/debugger-ui.
  3. Enable Pause On Caught Exceptions for a better debugging experience.
  4. Press Command + Option + I to open the Chrome Developer tools, or open it via View -> Developer -> Developer Tools.
  5. You should now be able to debug as you normally would.

React supported libraries & Integration

What is reselect and how it works?

Reselect is a selector library (for Redux) which uses memoization concept. It was originally written to compute derived data from Redux-like applications state, but it can’t be tied to any architecture or library.

Reselect keeps a copy of the last inputs/outputs of the last call, and recomputes the result only if one of the inputs changes. If the same inputs are provided twice in a row, Reselect returns the cached output. It’s memoization and cache are fully customizable.

What is Flow?

Flow is a static type checker designed to find type errors in JavaScript. Flow types can express much more fine-grained distinctions than traditional type systems. For example, Flow helps you catch errors involving null, unlike most type systems.

What is the difference between Flow and PropTypes?

Flow is a static analysis tool (static checker) which uses a superset of the language, allowing you to add type annotations to all of your code and catch an entire class of bugs at compile time.

PropTypes is a basic type checker (runtime checker) which has been patched onto React. It can’t check anything other than the types of the props being passed to a given component. If you want more flexible typechecking for your entire project Flow/TypeScript are appropriate choices.

How do you use Font Awesome icons in React?

The following steps followed to include Font Awesome in React:

  1. Install font-awesome:

    Terminal window
    $ npm install --save font-awesome
  2. Import font-awesome in your index.js file:

    import "font-awesome/css/font-awesome.min.css";
  3. Add Font Awesome classes in className:

    function MyComponent {
    return <div><i className={'fa fa-spinner'} /></div>
    }

What is React Dev Tools?

React Developer Tools let you inspect the component hierarchy, including component props and state. It exists both as a browser extension (for Chrome and Firefox), and as a standalone app (works with other environments including Safari, IE, and React Native).

The official extensions available for different browsers or environments.

  1. Chrome extension
  2. Firefox extension
  3. Standalone app (Safari, React Native, etc)

Why is DevTools not loading in Chrome for local files?

If you opened a local HTML file in your browser (file://...) then you must first open Chrome Extensions and check Allow access to file URLs.

How do you use Polymer in React?

You need to follow below steps to use Polymer in React,

  1. Create a Polymer element:

    <link
    rel="import"
    href="../../bower_components/polymer/polymer.html"
    />;
    Polymer({
    is: "calendar-element",
    ready: function () {
    this.textContent = "I am a calendar";
    },
    });
  2. Create the Polymer component HTML tag by importing it in a HTML document, e.g. import it in the index.html of your React application:

    <link
    rel="import"
    href="./src/polymer-components/calendar-element.html"
    />
  3. Use that element in the JSX file:

    export default function MyComponent {
    return <calendar-element />;
    }

What are the advantages of React over Vue.js?

React has the following advantages over Vue.js:

  1. Gives more flexibility in large apps developing.
  2. Easier to test.
  3. Suitable for mobile apps creating.
  4. More information and solutions available.

Note: The above list of advantages are purely opinionated and it vary based on the professional experience. But they are helpful as base parameters.

What is the difference between React and Angular?

Let’s see the difference between React and Angular in a table format.

ReactAngular
React is a library and has only the View layerAngular is a framework and has complete MVC functionality
React handles rendering on the server sideAngularJS renders only on the client side but Angular 2 and above renders on the server side
React uses JSX that looks like HTML in JS which can be confusingAngular follows the template approach for HTML, which makes code shorter and easy to understand
React Native, which is a React type to build mobile applications are faster and more stableIonic, Angular’s mobile native app is relatively less stable and slower
In React, data flows only in one way and hence debugging is easyIn Angular, data flows both way i.e it has two-way data binding between children and parent and hence debugging is often difficult

Note: The above list of differences are purely opinionated and it vary based on the professional experience. But they are helpful as base parameters.

Why React tab is not showing up in DevTools?

When the page loads, React DevTools sets a global named __REACT_DEVTOOLS_GLOBAL_HOOK__, then React communicates with that hook during initialization. If the website is not using React or if React fails to communicate with DevTools then it won’t show up the tab.

What are Styled Components?

styled-components is a JavaScript library for styling React applications. It removes the mapping between styles and components, and lets you write actual CSS augmented with JavaScript.

Can you give an example of Styled Components?

Let’s create <Title> and <Wrapper> components with specific styles for each.

import React from "react";
import styled from "styled-components";
// Create a <Title> component that renders an <h1> which is centered, red and sized at 1.5em
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
// Create a <Wrapper> component that renders a <section> with some padding and a papayawhip background
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;

These two variables, Title and Wrapper, are now components that you can render just like any other react component.

<Wrapper>
<Title>{"Let's start first styled component!"}</Title>
</Wrapper>

What is Relay?

Relay is a JavaScript framework for providing a data layer and client-server communication to web applications using the React view layer.

Miscellaneous

What are the main features of Reselect library?

Let’s see the main features of Reselect library,

  1. Selectors can compute derived data, allowing Redux to store the minimal possible state.

  2. Selectors are efficient. A selector is not recomputed unless one of its arguments changes.

  3. Selectors are composable. They can be used as input to other selectors.

  4. Give an example of Reselect usage?

    Let’s take calculations and different amounts of a shipment order with the simplified usage of Reselect:

    import { createSelector } from "reselect";
    const shopItemsSelector = (state) => state.shop.items;
    const taxPercentSelector = (state) => state.shop.taxPercent;
    const subtotalSelector = createSelector(shopItemsSelector, (items) =>
    items.reduce((acc, item) => acc + item.value, 0)
    );
    const taxSelector = createSelector(
    subtotalSelector,
    taxPercentSelector,
    (subtotal, taxPercent) => subtotal * (taxPercent / 100)
    );
    export const totalSelector = createSelector(
    subtotalSelector,
    taxSelector,
    (subtotal, tax) => ({ total: subtotal + tax })
    );
    let exampleState = {
    shop: {
    taxPercent: 8,
    items: [
    { name: "apple", value: 1.2 },
    { name: "orange", value: 0.95 },
    ],
    },
    };
    console.log(subtotalSelector(exampleState)); // 2.15
    console.log(taxSelector(exampleState)); // 0.172
    console.log(totalSelector(exampleState)); // { total: 2.322 }

Can Redux only be used with React?

Redux can be used as a data store for any UI layer. The most common usage is with React and React Native, but there are bindings available for Angular, Angular 2, Vue, Mithril, and more. Redux simply provides a subscription mechanism which can be used by any other code.

Do you need to have a particular build tool to use Redux?

Redux is originally written in ES6 and transpiled for production into ES5 with Webpack and Babel. You should be able to use it regardless of your JavaScript build process. Redux also offers a UMD build that can be used directly without any build process at all.

How Redux Form initialValues get updated from state?

You need to add enableReinitialize : true setting.

const InitializeFromStateForm = reduxForm({
form: "initializeFromState",
enableReinitialize: true,
})(UserEdit);

If your initialValues prop gets updated, your form will update too.

How React PropTypes allow different types for one prop?

You can use oneOfType() method of PropTypes.

For example, the height property can be defined with either string or number type as below:

Component.propTypes = {
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};

Can you import an SVG file as react component?

You can import SVG directly as component instead of loading it as a file. This feature is available with react-scripts@2.0.0 and higher.

import { ReactComponent as Logo } from "./logo.svg";
const App = () => (
<div>
{/* Logo is an actual react component */}
<Logo />
</div>
);

Note: Don’t forget about the curly braces in the import.

What is render hijacking in react?

The concept of render hijacking is the ability to control what a component will output from another component. It means that you decorate your component by wrapping it into a Higher-Order component. By wrapping, you can inject additional props or make other changes, which can cause changing logic of rendering. It does not actually enable hijacking, but by using HOC you make your component behave differently.

Do I need to keep all my state into Redux? Should I ever use react internal state?

It is up to the developer’s decision, i.e., it is developer’s job to determine what kinds of state make up your application, and where each piece of state should live. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as β€œis this dropdown currently open”, inside a component’s internal state.

Here are the rules of thumb to determine what kind of data should be put into Redux

  1. Do other parts of the application care about this data?
  2. Do you need to be able to create further derived data based on this original data?
  3. Is the same data being used to drive multiple components?
  4. Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?
  5. Do you want to cache the data (i.e, use what’s in state if it’s already there instead of re-requesting it)?

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();

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. Here 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

What are the advantages of formik over redux form library?

Here are the main reasons to recommend formik over redux form library,

  1. The form state is inherently short-term and local, so tracking it in Redux (or any kind of Flux library) is unnecessary.
  2. Redux-Form calls your entire top-level Redux reducer multiple times ON EVERY SINGLE KEYSTROKE. This way it increases input latency for large apps.
  3. Redux-Form is 22.5 kB minified gzipped whereas Formik is 12.7 kB

What is your favorite React stack?

Even though the tech stack varies from developer to developer, the most popular stack is used in react boilerplate project code. It mainly uses Redux and redux-saga for state management and asynchronous side-effects, react-router for routing purpose, styled-components for styling react components, axios for invoking REST api, and other supported stack such as webpack, reselect, ESNext, Babel. You can clone the project https://github.com/react-boilerplate/react-boilerplate and start working on any new react project.

How do you add Bootstrap to a react application?

Bootstrap can be added to your React app in a three possible ways,

  1. Using the Bootstrap CDN: This is the easiest way to add bootstrap. Add both bootstrap CSS and JS resources in a head tag.
  2. Bootstrap as Dependency: If you are using a build tool or a module bundler such as Webpack, then this is the preferred option for adding Bootstrap to your React application
    npm install bootstrap
  3. React Bootstrap Package: In this case, you can add Bootstrap to our React app is by using a package that has rebuilt Bootstrap components to work particularly as React components. Below packages are popular in this category,
    1. react-bootstrap
    2. reactstrap

Can you list down top websites or applications using react as front end framework?

Here are the top 10 websites using React as their front-end framework,

  1. Facebook
  2. Uber
  3. Instagram
  4. WhatsApp
  5. Khan Academy
  6. Airbnb
  7. Dropbox
  8. Flipboard
  9. Netflix
  10. PayPal

React does not have any opinion about how styles are defined but if you are a beginner then good starting point is to define your styles in a separate *.css file as usual and refer to them using className. This functionality is not part of React but came from third-party libraries. But If you want to try a different approach(CSS-In-JS) then styled-components library is a good option.

Do I need to rewrite all my class components with hooks?

No. But you can try Hooks in a few components(or new components) without rewriting any existing code. Because there are no plans to remove classes in ReactJS.

How do you access imperative API of web components?

Web Components often expose an imperative API to implement its functions. You will need to use a ref to interact with the DOM node directly if you want to access imperative API of a web component. But if you are using third-party Web Components, the best solution is to write a React component that behaves as a wrapper for your Web Component.

Do browsers understand JSX code?

No, browsers can’t understand JSX code. You need a transpiler to convert your JSX to regular Javascript that browsers can understand. The most widely used transpiler right now is Babel.

Describe data flow in react?

React implements one-way reactive data flow using props which reduce boilerplate and is easier to understand than traditional two-way data binding.

Should I learn ES6 before learning ReactJS?

No, you don’t have to learn es2015/es6 to learn react. But you may find many resources or React ecosystem uses ES6 extensively. Let’s see some of the frequently used ES6 features,

  1. Destructuring: To get props and use them in a component

    // in es 5
    var someData = this.props.someData;
    var dispatch = this.props.dispatch;
    // in es6
    const { someData, dispatch } = this.props;
  2. Spread operator: Helps in passing props down into a component

    // in es 5
    <SomeComponent someData={this.props.someData} dispatch={this.props.dispatch} />
    // in es6
    <SomeComponent {...this.props} />
  3. Arrow functions: Makes compact syntax

    // es 5
    var users = usersList.map(function (user) {
    return <li>{user.name}</li>;
    });
    // es 6
    const users = usersList.map((user) => <li>{user.name}</li>);

What is the difference between Imperative and Declarative in React?

Imagine a simple UI component, such as a β€œLike” button. When you tap it, it turns blue if it was previously grey, and grey if it was previously blue.

The imperative way of doing this would be:

if (user.likes()) {
if (hasBlue()) {
removeBlue();
addGrey();
} else {
removeGrey();
addBlue();
}
}

Basically, you have to check what is currently on the screen and handle all the changes necessary to redraw it with the current state, including undoing the changes from the previous state. You can imagine how complex this could be in a real-world scenario.

In contrast, the declarative approach would be:

if (this.state.liked) {
return <blueLike />;
} else {
return <greyLike />;
}

Because the declarative approach separates concerns, this part of it only needs to handle how the UI should look in a specific state, and is therefore much simpler to understand.

What are the benefits of using TypeScript with ReactJS?

Below are some of the benefits of using TypeScript with ReactJS,

  1. You can use latest JavaScript features
  2. Use of interfaces for complex type definitions
  3. IDEs such as VS Code was made for TypeScript
  4. Avoid bugs with the ease of readability and Validation

When to use client and server components?

You can efficiently build nextjs application if you are aware about which part of the application needs to use client components and which other parts needs to use server components. The common cases of both client and server components are listed below:

Client components:

  1. Whenever your need to add interactivity and event listeners such as onClick(), onChange(), etc to the pages
  2. If you need to use State and Lifecycle Effects like useState(), useReducer(), useEffect() etc.
  3. If there is a requirement to use browser-only APIs.
  4. If you need to implement custom hooks that depend on state, effects, or browser-only APIs.
  5. There are React Class components in the pages.

Server components:

  1. If the component logic is about data fetching.
  2. If you need to access backend resources directly.
  3. When you need to keep sensitive information((access tokens, API keys, etc) ) on the server.
  4. If you want reduce client-side JavaScript and placing large dependencies on the server.

What are the differences between page router and app router in nextjs?

Next.js provides two different routing systems: the Page Router (traditional) and the App Router (introduced in Next.js 13). The App Router is built on React Server Components and offers more powerful features for modern web applications.

Here are the main differences between them:

FeaturePage RouterApp Router
DirectoryUses pages/ directoryUses app/ directory
RoutingFile-based routing with files like pages/about.jsFile-based routing with folders and special files like app/about/page.js
ComponentsAll components are Client Components by defaultAll components are Server Components by default
LayoutsCustom _app.js and _document.js for shared layoutsNative nested layouts using layout.js files
Data FetchingUses getServerSideProps, getStaticProps, and getInitialPropsUses async/await in Server Components with native fetch
Loading StatesManual implementation requiredBuilt-in loading.js for streaming and suspense
Error HandlingCustom _error.js pageBuilt-in error.js for error boundaries at any level
StreamingLimited supportBuilt-in support for streaming with Suspense
Server ActionsNot availableNative support for server-side mutations
MetadataUsing Head component from next/headNative Metadata API with metadata object or generateMetadata function
RenderingSSR, SSG, ISR, and CSRSSR, SSG, ISR, CSR plus React Server Components

Example of Page Router structure:

pages/
β”œβ”€β”€ index.js // Home page (/)
β”œβ”€β”€ about.js // About page (/about)
β”œβ”€β”€ _app.js // Custom App component
β”œβ”€β”€ _document.js // Custom Document
└── posts/
└── [id].js // Dynamic route (/posts/:id)

Example of App Router structure:

app/
β”œβ”€β”€ page.js // Home page (/)
β”œβ”€β”€ layout.js // Root layout
β”œβ”€β”€ loading.js // Loading UI
β”œβ”€β”€ error.js // Error UI
β”œβ”€β”€ about/
β”‚ └── page.js // About page (/about)
└── posts/
└── [id]/
└── page.js // Dynamic route (/posts/:id)

Note: The App Router is recommended for new Next.js applications as it provides better performance, simpler data fetching patterns, and improved developer experience with React Server Components.

Share & Connect