Background

React is a popular tool allows to build UI components using front-end JavaScript library. React is also known as React.js or ReactJS.

Why to read this article?

In this article, questions having multiple options. Correct answers are given along with detailed description and with code examples. Hence, one can have actual idea about the concept or feature.

Questions

  1. What is output of 2 + '2' in JavaScript?

  2. How to manage user input in React forms?

  3. Which is correct way to import React component?

  4. Which is NOT valid way to style components in React?

  5. How to pass data from parent component to child component in React?

  6. What is purpose of render() method in React component?

  7. What is purpose of 'ref' attribute in React?

  8. What are props in React?

  9. Which method is used to initialize state in React component?

  10. What is purpose of React.StrictMode component?

  11. What is use of PropTypes in React?

  12. How to update state of functional component in React?

  13. Which is NOT valid way to define inline styles in React?

  14. Which is correct way to render list of items in React?

  15. Which is correct way to render React component?

  16. Which command is used to create new React app?

  17. What is use of React.createElement() function?

  18. How to conditionally render elements in React?

  19. Which is NOT valid way to define React component?

  20. What is purpose of keys in React lists?

  21. Which is NOT valid JSX syntax?

  22. What is use of React.Fragment component?

  23. Which is correct way to handle forms in React?

  24. Which hook is used to perform side effects in functional component?

  25. Which is recommended way to handle events in React?

Answers

1. What is output of 2 + '2' in JavaScript?

Correct Answer:

Explanation:

JavaScript uses type coercion with + operator. Hence, it gives '22' output for 2 + '2'.

Here, If either operand is a string then JavaScript converts other operand to a string. Then it performs string concatenation instead of arithmetic addition.

Concatenation performed for string involvement. + performs both operations addition and string concatenation.

Evaluation

Example

2. How to manage user input in React forms?

Correct Answer:

Explanation:

Controlled components is used to manage user input in React forms using below steps:

JSX

import { useState } from "react";
function Form() {
  const [name, setName] = useState("");
  return (
    <input type="text" value={name} onChange={(e) => setName(e.target.value)}   />
  );
}

Here, input is controlled and useState() manages input value.

Why other options are incorrect?

3. Which is correct way to import React component?

Correct Answer:

Explanation:

React and modern JavaScript are using ES Modules. Common and correct way to import component is using default import with assumption of component is exported as default export.

JSX - React component export

// MyComponent.jsx
export default function MyComponent() {
     return <div>Hello</div>;
}

JSX - Correct import

import MyComponent from './MyComponent';

This is a standard and recommended pattern used in modern React applications.

Why other options are incorrect?

4. Which is NOT valid way to style components in React?

Correct Answer:

Explanation:

Inline styles, External CSS files, and Styled-components library are valid ways to style components in React.

HTML style attribute is not valid in React. String-based style attributes are not supported in. Styles must be provided as JavaScript object instead of string.

JSX

<div style="color: red;">Hello</div>

Why other options are correct?

JSX

<div style={{ color: "red", fontSize: "16px" }}>Hello</div>

JSX

import "./styles.css";
<div className="container">Hello</div>

JSX

import styled from "styled-components";
const Button = styled.button`
  background: blue;
  color: white;
`;

5. How to pass data from parent component to child component in React?

Correct Answer:

Explanation:

Props is short form of properties. It is a standard and primary way to pass data from a parent component to child component.

JSX

function Parent() {
     return <Child message="Hello from Parent" />;
}

function Child(props) {
     return <p>{props.message}</p>;
}

Here, Parent passes data i.e. message to child. Child receives it through props.

Why other options are incorrect?

6. What is purpose of render() method in React component?

Correct Answer:

Explanation:

Render() method is used in class components to describe how UI should looks like. It returns JSX which React converts into DOM elements. React uses returned JSX to update DOM.

JSX

class MyComponent extends React.Component {
     render() {
          return <h1>Hello, React!</h1>;
     }
}

Here, render() returns a markup which appears on screen.

Why other options are incorrect?

7. What is purpose of 'ref' attribute in React?

Correct Answer:

Explanation:

The 'ref' attribute is used to get direct access to the DOM element. It is mainly used to focus an input or to measure DOM element. It can trigger animations and can integrate thirdparty DOM libraries.

JSX

import { useRef } from "react";
     function MyComponent() {
          const inputRef = useRef(null);
          const focusInput = () => {
               inputRef.current.focus();
          };
     return (
          <>
                                             <input ref={inputRef} />
                                             <button onClick={focusInput}>Focus</button>
                                   </>
    );
}

Here, ref provides a reference to actual <input> DOM element.

Why other options are incorrect?

8. What are props in React?

Correct Answer:

Explanation:

Props is short form of properties. It is used to pass data from parent component to child component. It is read-only. Child component can’t modify props it receives.

JSX

function Parent() {
     return <Child name="React" />;
}

function Child(props) {
     return <h1>Hello, {props.name}!</h1>;
}

Here, name is a prop. "React" is value and passed from Parent to Child component. Child accesses it using props.name.

Why other options are incorrect?

9. Which method is used to initialize state in React component?

Correct Answer:

Explanation:

useState() is standard approach to initialize state in React components. It is recommended and mostly used way to initialize state especially in functional components in modern React apps.

JSX

import { useState } from "react";

function Counter() {
     const [count, setCount] = useState(0);
     return <p>{count}</p>;
}

Here, useState(0) initializes state with value 0.

Why other options are incorrect?

JSX

class Counter extends React.Component {
     constructor(props) {
          super(props);
          this.state = { count: 0 };
     }
}

Here, this is valid but class components are now no longer preferred approach in modern React app.

10. What is purpose of React.StrictMode component?

Correct Answer:

Explanation:

React.StrictMode is development-only helper component. It enables additional checks and warnings for all the components wrapped inside it. It is used to help developers to identify the potential problems early in development process. It doesn’t affect any production builds. It runs only in development.

StrictMode mode gives warnings about legacy APIs and identifies unexpected side effects. It executes couple of methods twice such as useEffect to cleanup surface bugs. It prepares code for future React features and also detects unsafe lifecycle methods.

JSX

import React from "react";

function App() {
     return (
          <React.StrictMode>
                                        <MyComponent />
                                   </React.StrictMode>
     );
}

Here, component is wrapped in StrictMode therefore React performs additional extra validations on MyComponent component and on it’s children.

Why other options are incorrect?

11. What is use of PropTypes in React?

Correct Answer:

Explanation:

PropTypes are used for type checking props passed to the component. It helps developers to catch bugs early by validating that components receive props of correct type and structure. It runs only in development mode. It don’t impact production performance.

JSX

import PropTypes from "prop-types";

function User({ name, age }) {
     return <p>{name} is {age} years old</p>;
}

User.propTypes = {
     name: PropTypes.string.isRequired,
     age: PropTypes.number
};

Here, name prop is required and must be type of string while age is optional and must be number. React shows warning in console if props are incorrect.

Why other options are incorrect?

12. How to update state of functional component in React?

Correct Answer:

Explanation:

State of a functional component in React is updated using useState() hook. It provides current state value. It also provides a function to update the state value.

JSX

import { useState } from "react";

function Counter() {
     const [count, setCount] = useState(0);
     return (
          <>
                                        <p>Count: {count}</p>
                                        <button onClick={() => setCount(count + 1)}>Increment</button>
                                   </>
     );
}

Here, count is a state variable and setCount is used to update state value. State updating triggers re-render.

Why other options are incorrect?

13. Which is NOT valid way to define inline styles in React?

Correct Answer:

Explanation:

In React, inline styles must be provided as JavaScript object instead of string such as plain HTML.

JSX

<div style="color: red"></div>

Here, This is invalid in JSX although valid in HTML. In React, style attribute must be object instead of string. Styles written as string might cause error or ignored.

Why other options are correct?

Following all are valid way to define inline styles in React:

14. Which is correct way to render list of items in React?

Correct Answer:

Explanation:

“Using the map() method” is a correct and recommended way to render a list of items in React. map() is JavaScript’s method which returns JSX elements. map() iterates over array and returns new array of JSX elements. It perfectly fits to render lists in React.

JSX

const items = ["Apple", "Banana", "Cherry"];

function List() {
     return (
          <ul>
                                        {items.map((item, index) => (
                                             <li key={index}>{item}</li>
                                        ))}
                                   </ul>
     );
}

Here, map() transforms each array item into <li> element. Key is given to each list item so that React can effectively track list changes.

Why other options are incorrect?

15. Which is correct way to render React component?

Correct Answer:

Explanation:

React components are rendered using JSX syntax similar to HTML. Using self-closing tag and opening-closing tags if component has children are two valid ways to render a React component.

JSX

<MyComponent />

Here, it instantiate to MyComponent. For function component it is called and for class component it invokes render() method. It inserts resulting UI inside JSX tree.

Why other options are incorrect?

16. Which command is used to create new React app?

Correct Answer:

Explanation:

Create React App is a tool which is provided by React team. It is used to create a new React app quickly. It also makes default configurations such as Babel, Webpack, ESLint, etc.

Shell

npx create-react-app my-app

Here, It sets up complete React development environment. It doesn’t require any manual configuration. It allows to start coding immediately.

Why other options are incorrect?

17. What is use of React.createElement() function?

Correct Answer:

Explanation:

React.createElement() is low-level React API. It creates React element i.e. plain JavaScript object that describes what should appear in UI. It do none of the above action directly. Virtual DOM is not the real DOM.

React.createElement() actually creates a React Element. It doesn’t create component or DOM node. This created element is used later on during reconciliation and rendering process.

Syntax

React.createElement(
type,
props,
children
);

Example

React.createElement("h1", null, "Hello React");

It produces object similar to:

JavaScript

{
     type: "h1",
     props: { children: "Hello React" }
}

Why other options are incorrect?

18. How to conditionally render elements in React?

Correct Answer:

Explanation:

In React, elements can be conditionally render elements in following ways based on situation:

Why other options are correct?

JSX

function Greeting({ isLoggedIn }) {
     if (isLoggedIn) {
          return <h1>Welcome back!</h1>;
     }
     return <h1>Please sign in.</h1>;
}

JSX

function Greeting({ isLoggedIn }) {
     return (
          <h1>{isLoggedIn ? "Welcome back!" : "Please sign in."}</h1>
     );
}

JSX

function Notifications({ hasMessages }) {
     return (
          <>
                                                  {hasMessages && <p>You have new messages</p>}
                                    </>
     );
}

19. Which is NOT valid way to define React component?

Correct Answer:

Explanation:

Class component, Function component and Stateless component are valid ways to define React component.

Object component is not a valid way to define React component. There is no such concept in React. It is not valid React component nor supported by React. React component must be either functional or class instead of plain object.

Why other options are correct?

JSX

class MyComponent extends React.Component {
     render() {
          return <h1>Hello</h1>;
     }
}

JSX

function MyComponent() {
     return <h1>Hello</h1>;
}

JSX

const MyComponent = () => <h1>Hello</h1>;

20. What is purpose of keys in React lists?

Correct Answer:

Explanation:

Keys are used in React lists to uniquely identify elements in list. Using it React can efficiently update and re-render only changed items in list instead of re-rendering entire list. While doing list rendering keys are used to identify which item is added, removed, updated, or reordered.

JSX

const items = ["Apple", "Banana", "Cherry"];
function List() {
     return (
          <ul>
                                         {items.map((item, index) => (
                                             <li key={index}>{item}</li>
                                         ))}
                                   </ul>
     );
}

Here, key uniquely identifies each <li> element. Instead of array index, use a stable unique ID such as database’s table column ID.

Why other options are incorrect?

21. Which is NOT valid JSX syntax?

Correct Answer:

Explanation:

JSX is short form of JavaScript XML. It is React’s syntax extension for JavaScript. In JSX, some HTML attributes are renamed to avoid conflicts with JavaScript reserved key words.

<div class="container"></div> - It is not a valid JSX syntax. Here, class is reserved keyword in JavaScript. JSX requires to use className instead instead of class.

Why other options are correct?

22. What is use of React.Fragment component?

Correct Answer:

Explanation:

The use of React.Fragment component is to group multiple elements without adding extra DOM node. It is used to wrap multiple child elements and they can be returned from component without adding extra DOM node. In React, component must be returned as a single parent element and this can be managed perfectly using fragments.

JSX

import React from "react";
function MyComponent() {
     return (
          <React.Fragment>
                                             <h1>Title</h1>
                                             <p>Description</p>
                                  </React.Fragment>
     );
}

Here, It renders <h1> and <p> as siblings in the DOM, without adding extra <div>.

JSX - shorter syntax, behaves same way

function MyComponent() {
     return (
          <>
                                             <h1>Title</h1>
                                             <p>Description</p>
                                   </>
     );
}

Why other options are incorrect?

JSX

{/* This is a comment */}

23. Which is correct way to handle forms in React?

Correct Answer:

Explanation:

In React, forms are mainly handled using controlled components. onSubmit and onChange event handler is a correct way to handle forms in React.

onSubmit -

JSX

function MyForm() {
     const handleSubmit = (e) => {
          e.preventDefault();
          console.log("Form submitted");
     };
     return (
          <form onSubmit={handleSubmit}>
                                             <button type="submit">Submit</button>
                                   </form>
     );
}

onChange -

JSX

function MyForm() {
     const [name, setName] = React.useState("");
     return (
          <input
                                             type="text"
                                             value={name}
                                             onChange={(e) => setName(e.target.value)}
                                   />
     );
}

Why other options are incorrect?

24. Which hook is used to perform side effects in functional component?

Correct Answer:

Explanation:

useEffect() hook is used to perform side effects in functional components. Side effects commonly used to fetch data from API, subscribe to events, update DOM manually, set up timers and intervals, logging, perform side effects.

JSX

import { useEffect } from "react";

function Example() {
     useEffect(() => {
          console.log("Component mounted");
          return () => {
               console.log("Component unmounted");
          };
     }, []);
     return <div>Hello</div>;
}

Here, effect runs after component renders and cleanup function runs when component unmounts.

Why other options are incorrect?

25. Which is recommended way to handle events in React?

Correct Answer:

Explanation:

In React, passing callback functions as props is a common and recommended pattern for handling events. It passes callback functions as props from parent to child component. It keeps data flow unidirectional.

JSX

function Parent() {
     const handleClick = () => {
          console.log("Button clicked");
     };
     return <Child onClick={handleClick} />;
}

function Child({ onClick }) {
     return <button onClick={onClick}>Click Me</button>;
}

Here, Parent defines event logic and child triggers it via prop. This makes component reusable and maintainable.

Why other options are incorrect?

JSX

<button onClick={() => console.log("Clicked")} />

Summary

Here, for each and every question; First, question is mentioned with multiple possible answers. And then, possible correct options are given. After that, detailed explanation is described with theory concept as well as with code samples. Lastly, it is mentioned why the other options are in-correct or in-appropriate.

Now, I believe one will be able to properly answer or to understand most popular React Fundamental interview questions. These questions will be useful to both beginner or intermediate React developers.