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?
To check your React fundamental knowledge.
To understand React features along with their use-case and example.
To crack some certifications or interviews of React.
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
What is output of 2 + '2' in JavaScript?
How to manage user input in React forms?
Which is correct way to import React component?
Which is NOT valid way to style components in React?
How to pass data from parent component to child component in React?
What is purpose of render() method in React component?
What is purpose of 'ref' attribute in React?
What are props in React?
Which method is used to initialize state in React component?
What is purpose of React.StrictMode component?
What is use of PropTypes in React?
How to update state of functional component in React?
Which is NOT valid way to define inline styles in React?
Which is correct way to render list of items in React?
Which is correct way to render React component?
Which command is used to create new React app?
What is use of React.createElement() function?
How to conditionally render elements in React?
Which is NOT valid way to define React component?
What is purpose of keys in React lists?
Which is NOT valid JSX syntax?
What is use of React.Fragment component?
Which is correct way to handle forms in React?
Which hook is used to perform side effects in functional component?
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 + 2 will gives output 2.
2 - '2' will gives output 0, because - forces numeric conversion.
'2' * 2 will gives output 4.
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:
Step-1: Form input’s value is stored in React component state.
Step-2: Changes to input trigger an onChange handler.
Step-3: State is updated using useState().
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?
By directly manipulating the DOM - React avoids direct DOM manipulations. It uses virtual DOM to reflect only changes using state updates.
By using useEffect() - It is used for side effects such as API calls, subscriptions, timers, etc. It is not used to manage form input values.
3. Which is correct way to import React component?
A. import MyComponent from './MyComponent';
B. require('./MyComponent');
C. import { MyComponent } from './MyComponent';
D. import MyComponent from './MyComponent.js';
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?
require('./MyComponent'); - It is used in CommonJS instead of ES Modules. It is valid in Node.js, but not standard in modern React apps. It is not used with JSX and modern tooling.
import { MyComponent } from './MyComponent'; - It is only valid if component is exported as named export.
import MyComponent from './MyComponent.js'; - It can work, but not standard because .js extension is usually omitted. Webpack and Vite Bundlers resolves it automatically.
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?
A. Using context
B. Using state
C. Using props
D. Using refs
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?
Using context - It passes data through component tree instead of prop drilling. It is not the basic or primary method to pass data to children. It is mainly used for global or shared data such as themes, auth, locale, etc.
Using state - It is owned by component. State is not direct mechanism to pass data to children.
Using refs - It is used to access DOM elements or component instances. It can’t used to pass data between components.
6. What is purpose of render() method in React component?
A. It is responsible for updating the component's state
B. It is called after the component has been rendered to the DOM
C. It is used to perform side effects in a component
D. It returns the HTML markup to be displayed by the 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?
It is responsible for updating the component's state - State update is done through this.setState() instead of render(). Inside render() updates to state can cause infinite loops.
It is called after the component has been rendered to the DOM - render() is called before React updates the DOM.
It is used to perform side effects in a component - Side effects used with API calls, subscriptions, timers, etc. It belongs to lifecycle methods componentDidMount and componentDidUpdate. For functional components it belongs to useEffect() hooks.
7. What is purpose of 'ref' attribute in React?
A. It references another component in the virtual DOM
B. It provides a reference to a DOM element created by a React component
C. It allows you to define default props for a component
D. It specifies the relationship between a parent and child component
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?
It references another component in the virtual DOM - refs points to actual DOM elements or to instances of component.
It allows you to define default props for a component - Default props defines through defaultProps as well as using default function parameters.
It specifies the relationship between a parent and child component - Props or component nesting allows to define parent-child relationship.
8. What are props in React?
A. Properties that are passed from parent to child components
B. Methods used to manipulate state in React components
C. Functions used to handle events in React components
D. Built-in React components for common UI elements
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?
Methods used to manipulate state in React components - State is managed using useState() or setState() instead of props.
Functions used to handle events in React components - Event handlers such onClick, onChange, etc. can passed as props. Although props themselves are not event-handling functions.
Built-in React components for common UI elements - React provides several built-in elements such as <div>, <span>, etc. Props are data instead of components.
9. Which method is used to initialize state in React component?
A. this.state()
B. useState()
C. initState()
D. constructor()
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?
this.state() - no such method exists.
initState() - no such method exists.
constructor() - It is only used in class components. It is now considered as legacy for most new React development.
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?
A. It ensures that all state updates are synchronized
B. It disables certain React features for performance optimization
C. It enforces strict mode for all components within its sub-tree
D. It prevents components from rendering unnecessarily
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?
It ensures that all state updates are synchronized - State synchronization is managed through React’s update mechanism.
It disables certain React features for performance optimization - StrictMode does just opposite. It performs extra renders in development to expose issues.
It prevents components from rendering unnecessarily - It is handled through React.memo, useMemo, or shouldComponentUpdate techniques.
11. What is use of PropTypes in React?
A. To define types of props expected by a component
B. To validate structure of the component's state
C. To handle errors that occur during rendering
D. To provide default values for props
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?
To validate structure of the component's state - PropTypes validates props instead of component’s state. State validation can be handled either manually or via TypeScript.
To handle errors that occur during rendering - Rendering errors handles using Error Boundaries instead of PropTypes.
To provide default values for props - Default values can be set either using defaultProps or using default parameters in function components.
12. How to update state of functional component in React?
A. By calling this.setState()
B. By directly modifying state object
C. By using useState() hook
D. By passing props from a parent component
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?
By calling this.setState() - It is used in class components only instead of functional components.
By directly modifying state object - Direct state modification is not allowed in React.
By passing props from a parent component - Props is read-only. It can’t be used to update component state.
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:
Inline style using object i.e. <div style={{ color: 'red' }}>
Inline style using variable i.e. <div style={styles}> and before that store style into variable such as const styles = { color: 'red' };
CSS class is not inline but valid React syntax i.e. <div className="red"> and this method allows to use external or modular CSS.
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?
Using loop in JSX - JSX does not support traditional loops (such as for or while) directly inside markup.
Using forEach() method - forEach() doesn’t return new array but it returns undefined. Hence, it can’t be used directly in JSX.
Using for loop - for loop doesn’t return array of elements while React requires array of elements for rendering lists.
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?
{MyComponent} - It can’t render component. It only references component definition.
render(MyComponent) - This is not valid React API.
React.render(MyComponent) - React.render does not exist. ReactDOM can handled rendering instead of React.
16. Which command is used to create new React app?
A. create-react-app
B. npm init react-app
C. start-react-app
D. react-init
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?
npm init react-app - It is not valid command.
start-react-app - It doesn’t exist.
react-init - It is not a React CLI tool.
17. What is use of React.createElement() function?
A. Creates new React component
B. Renders React component to the DOM
C. Creates new DOM element
D. None of the above
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?
Creates new React component - Component is created or defined using function or class instead of createElement().
Renders React component to the DOM - ReactDOM.createRoot(...).render(...) is used to render a React component to DOM.
Creates new DOM element - React’s renderer (ReactDOM) is used to create a new DOM element instead of createElement().
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:
Using if statements - primarily used for complex logic.
Using ternary operators - mainly used for inline conditions.
Using logical && operator - commonly used to render only on true condition.
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?
A. Class component
B. Function component
C. Object component
D. Stateless 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?
A. They control the styling of list items
B. They determine the order in which list items are rendered
C. They provide a unique identifier for each list item
D. They are used to specify the data type of list items
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?
They control the styling of list items - Styling is handled using CSS, className, or inline styles.
They determine the order in which list items are rendered - Order is determined using array order.
They are used to specify the data type of list items - React keys are not related to data types. It is used for unique identification and reconciliation.
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?
<div className="container"></div> - It is a correct way to apply CSS classes in JSX.
<div></div> - It is valid JSX element.
<div>{variable}</div> - Embedding JavaScript expressions inside {} is allowed in JSX.
22. What is use of React.Fragment component?
A. To group multiple elements without adding an extra DOM node
B. To create a new React component
C. To add comments to JSX
D. To handle asynchronous operations
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?
To create a new React component - Fragment can’t be used to create a new React component, because Fragment is not component. Hence, it will not allow to define logic in it. It is structural helper only.
To add comments to JSX - JSX has its own comment syntax.
JSX
{/* This is a comment */}
23. Which is correct way to handle forms in React?
A. Using the onSubmit event handler
B. Using the onChange event handler
C. Using the onClick event handler
D. Using the onFormSubmit event handler
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 -
It is used on form inputs such as input, textarea, select, etc.
It is updated to update component state as user types or changes values.
It is used to tracks user input.
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?
Using the onClick event handler - It triggers actions such as button click. It is not standard or recommended way to handle form submission in React forms.
Using the onFormSubmit event handler - It does not exist as it is invalid React or HTML event.
24. Which hook is used to perform side effects in functional component?
A. useState()
B. useEffect()
C. useContext()
D. useReducer()
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?
useState() - It is used to manage state instead of to perform side effects.
useContext() - It is used to consume values from React Context not for side effects.
useReducer() - It is used for complex state management such as Redux patterns.
25. Which is recommended way to handle events in React?
A. Inline event handlers
B. Using event listeners with JavaScript
C. Adding event delegation
D. Passing callback functions as props
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")} />
Using event listeners with JavaScript - It is not recommended. Adding event listeners with addEventListener is uncommon.
Adding event delegation - React internally handles event delegation. Hence, developers typically do not implement it manually.
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.