1. What is React and who created it?
Difficulty: EasyType: SubjectiveTopic: React Basics
React is an open-source JavaScript library developed by Facebook (now Meta) for building user interfaces, especially single-page applications. It helps developers create reusable UI components that update efficiently when data changes.
2. What are the main features of React?
Difficulty: EasyType: SubjectiveTopic: React Basics
Main features include the use of Virtual DOM for performance, component-based architecture for reusability, one-way data flow for predictability, and JSX for writing UI with HTML-like syntax inside JavaScript.
3. Explain the scope and growth of React in the web development ecosystem.
Difficulty: EasyType: SubjectiveTopic: React Basics
React is one of the most popular front-end libraries today. It has a large developer community, strong ecosystem, and is widely used in production by companies like Facebook, Instagram, and Airbnb. Its simple learning curve and reusable components make it ideal for fast-growing projects.
4. What are the advantages of using React?
Difficulty: EasyType: SubjectiveTopic: React Basics
React is fast thanks to Virtual DOM, SEO-friendly with server-side rendering, easy to learn, allows reusable components, and provides great developer tools. Its component model also promotes clean, maintainable code.
5. What are the limitations of React?
Difficulty: EasyType: SubjectiveTopic: React Basics
React is only a library, not a full framework. It requires learning JSX and other tools like routing or state management separately. Beginners might find it complex due to the large ecosystem.
6. What is JSX? Why do we use it in React?
Difficulty: EasyType: SubjectiveTopic: JSX
JSX stands for JavaScript XML. It allows developers to write HTML-like syntax inside JavaScript, making UI creation easier and more readable. React converts JSX into standard JavaScript using React.createElement() calls.
Example Code
const element = <h1>Hello, React!</h1>;
// Compiles to: React.createElement('h1', null, 'Hello, React!');7. Can we write React without JSX? If yes, how?
Difficulty: MediumType: SubjectiveTopic: JSX
Yes, React can be written without JSX by using React.createElement() directly. JSX is just a syntax sugar that makes code easier to read but not mandatory.
Example Code
const element = React.createElement('h1', null, 'Hello React without JSX');8. What is the difference between Real DOM and Virtual DOM?
Difficulty: MediumType: SubjectiveTopic: Rendering
The Real DOM updates the UI directly and is slow for frequent changes. The Virtual DOM is a lightweight copy stored in memory that React updates first, and only the differences are applied to the real DOM, making it much faster.
9. How does React use the virtual DOM to render the UI efficiently?
Difficulty: MediumType: SubjectiveTopic: Rendering
React keeps two versions of the Virtual DOM—previous and current. When a change occurs, React compares them (diffing) and updates only the changed parts in the real DOM, making rendering fast and efficient.
10. What are keys in React and why are they important?
Difficulty: EasyType: SubjectiveTopic: Lists Keys
Keys are unique identifiers for elements in a list. They help React know which items have changed, been added, or removed, improving rendering efficiency and preventing re-rendering errors.
Example Code
const list = items.map(item => <li key={item.id}>{item.name}</li>);11. When should you use keys and what happens if you don’t provide them?
Difficulty: EasyType: SubjectiveTopic: Lists Keys
Keys should be used when rendering lists of elements. Without them, React cannot track item changes properly, leading to wrong re-renders or performance issues.
12. What are props in React?
Difficulty: EasyType: SubjectiveTopic: Props
Props (short for properties) are inputs passed from parent to child components. They are read-only and used to send data or event handlers into components.
Example Code
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}13. What are state and props in React? Compare them.
Difficulty: MediumType: SubjectiveTopic: State
Props are external and passed to components; they can’t be modified inside. State is internal data managed within a component using hooks like useState(). Props are for communication, while state is for managing local changes.
14. Explain the unidirectional data flow in React.
Difficulty: MediumType: SubjectiveTopic: Data Flow
In React, data flows in one direction — from parent to child through props. This predictable flow makes debugging and state management simpler.
15. What is the purpose of ReactDOM.render()?
Difficulty: EasyType: SubjectiveTopic: ReactDOM
ReactDOM.render() mounts or updates React elements into the DOM. It connects your React app to a real HTML container, typically linking JavaScript logic to browser display.
Example Code
ReactDOM.render(<App />, document.getElementById('root'));16. React is mainly used for developing ______.
Difficulty: EasyType: MCQTopic: React Basics
- Connectivity
- Database
- User interface
- Design platform
React focuses on building interactive user interfaces for web and mobile apps. It doesn't handle databases or backend logic.
Correct Answer: User interface
17. The keys given to a list of elements in React should be ______.
Difficulty: EasyType: MCQTopic: Lists Keys
- Not necessarily unique
- Unique among siblings
- Unique in the DOM
- None of the above
Keys must be unique only among siblings in a list, not globally. They help React track which list items change during rendering.
Correct Answer: Unique among siblings
18. ______ is a necessary API for every React.js component.
Difficulty: EasyType: MCQTopic: Rendering
- renderComponent
- render
- SetinitialComponent
- All of the above
Every React class component must implement a render() method that returns the component’s UI.
Correct Answer: render
19. What is React or ReactJS?
Difficulty: EasyType: MCQTopic: React Basics
- Component-based JavaScript library
- JavaScript framework
- JavaScript file
- None of the above
React is a component-based JavaScript library for building reusable UI elements and handling user interface logic efficiently.
Correct Answer: Component-based JavaScript library
20. What are functional components and class components in React?
Difficulty: EasyType: SubjectiveTopic: Components
Functional components are simple JavaScript functions that return JSX. Class components are ES6 classes that extend React.Component and use a render() method. Functional components are now preferred because they are simpler and support Hooks.
Example Code
// Functional Component
function Welcome() {
return <h1>Hello!</h1>;
}
// Class Component
class Welcome extends React.Component {
render() {
return <h1>Hello!</h1>;
}
}21. Explain the differences between functional and class components.
Difficulty: MediumType: SubjectiveTopic: Components
Functional components are lightweight and rely on Hooks for state and lifecycle. Class components use the render() method, have access to lifecycle methods, and use this.state. Hooks made functional components capable of everything classes can do with less code.
22. How do you handle props in functional vs class components?
Difficulty: EasyType: SubjectiveTopic: Props
In functional components, props are received as function arguments. In class components, they are accessed via this.props. Props are read-only in both cases.
Example Code
// Functional
function Hello(props) { return <p>{props.name}</p>; }
// Class
class Hello extends React.Component { render() { return <p>{this.props.name}</p>; } }23. How do you handle state in class vs functional components?
Difficulty: MediumType: SubjectiveTopic: State Mgmt
In class components, state is managed with this.state and updated using setState(). In functional components, state is handled with the useState() Hook. Both trigger re-renders when the state changes.
Example Code
// Functional
const [count, setCount] = useState(0);
// Class
this.state = { count: 0 };
this.setState({ count: this.state.count + 1 });24. What is useState() and how does it work?
Difficulty: EasyType: SubjectiveTopic: useState
useState() is a Hook that allows you to add state to functional components. It returns an array with the current state and a function to update it. When you call the setter function, React re-renders the component.
Example Code
const [name, setName] = useState('Guest');
setName('John'); // updates state and re-renders component25. What are controlled and uncontrolled components in React?
Difficulty: MediumType: SubjectiveTopic: Forms
In controlled components, form data is handled by React state. In uncontrolled components, the DOM itself manages the input value using refs. Controlled components provide better validation and consistency.
Example Code
// Controlled
<input value={text} onChange={(e) => setText(e.target.value)} />
// Uncontrolled
<input ref={inputRef} />26. Explain how refs work in uncontrolled components.
Difficulty: MediumType: SubjectiveTopic: Refs
Refs let you directly access a DOM element. In uncontrolled components, you use refs to read form values without React managing the input state.
Example Code
const inputRef = useRef();
const handleSubmit = () => {
alert(inputRef.current.value);
};27. Why are controlled components preferred for form handling?
Difficulty: MediumType: SubjectiveTopic: Forms
Controlled components make React the single source of truth for input values. This gives better control for validation, conditionally disabling inputs, and synchronizing with state.
28. How do you update state in a class component using setState()?
Difficulty: MediumType: SubjectiveTopic: State
setState() is used to update a class component’s state. It merges the new values with the existing state and triggers a re-render.
Example Code
this.setState({ count: this.state.count + 1 });29. Why shouldn’t you modify the state directly?
Difficulty: MediumType: SubjectiveTopic: State
Directly changing state (like this.state.count = 1) won’t trigger a re-render and can cause bugs. Always use setState() or Hooks to update state safely.
30. Explain the lifecycle of a React component (mount, update, unmount).
Difficulty: MediumType: SubjectiveTopic: Lifecycle
React component lifecycle includes three phases: Mounting (component created and added to DOM), Updating (re-render due to state/prop changes), and Unmounting (component removed from DOM). Hooks like useEffect can handle these phases in functional components.
31. What are side effects in React components?
Difficulty: MediumType: SubjectiveTopic: useEffect
Side effects are operations that affect something outside the component, like data fetching, subscriptions, or manually changing the DOM. These are handled using the useEffect Hook.
32. What are the two types of side effects?
Difficulty: MediumType: SubjectiveTopic: useEffect
There are two types: effects without cleanup (like API calls or logging) and effects with cleanup (like removing event listeners or cancelling timers). useEffect can handle both types using return functions.
Example Code
useEffect(() => {
const timer = setInterval(() => console.log('tick'), 1000);
return () => clearInterval(timer); // cleanup
}, []);33. How does React handle memory cleanup in useEffect()?
Difficulty: MediumType: SubjectiveTopic: useEffect
React cleans up side effects automatically when a component unmounts or before the effect runs again. Returning a cleanup function inside useEffect prevents memory leaks.
34. What does state represent in React?
Difficulty: EasyType: MCQTopic: State
- Internal storage of component
- External storage
- Permanent storage
- None of the above
State represents the internal data of a component that can change over time and cause re-renders when updated.
Correct Answer: Internal storage of component
35. What is the usage of setState()?
Difficulty: EasyType: MCQTopic: State
- Replace state fully
- Access earlier state
- Invoke code after update
- None of these
setState() schedules an update to the component’s state and re-renders it. It can also accept a callback that runs after the update is complete.
Correct Answer: Invoke code after update
36. What is used for passing data to a component from outside?
Difficulty: EasyType: MCQTopic: Props
- Render with arguments
- setState
- PropTypes
- props
Props are used to pass data from parent components to child components. They make components reusable and customizable.
Correct Answer: props
37. What are React Hooks and why were they introduced?
Difficulty: EasyType: SubjectiveTopic: Hooks
Hooks are special functions that let you use React features like state and lifecycle inside functional components. They were introduced to avoid complex class components and make logic reusable.
38. List some commonly used built-in Hooks.
Difficulty: EasyType: SubjectiveTopic: Hooks
Common Hooks include useState for state, useEffect for side effects, useRef for DOM refs, useContext for global context, useMemo and useCallback for optimization.
39. What is the purpose of useEffect()?
Difficulty: MediumType: SubjectiveTopic: useEffect
useEffect() is used to perform side effects like fetching data, updating the DOM, or setting up subscriptions after render. It replaces lifecycle methods like componentDidMount and componentDidUpdate.
Example Code
useEffect(() => {
console.log('Effect runs after render');
}, []);40. Explain the difference between effects with cleanup and without cleanup.
Difficulty: MediumType: SubjectiveTopic: useEffect
Effects without cleanup run once and don’t need cleanup, like fetching data. Effects with cleanup return a function that removes subscriptions or listeners when the component unmounts.
Example Code
useEffect(() => {
const timer = setInterval(() => console.log('tick'), 1000);
return () => clearInterval(timer);
}, []);41. What is the syntax of useEffect(callback, [dependencies])?
Difficulty: MediumType: SubjectiveTopic: useEffect
The useEffect hook accepts a function and an optional dependency array. The effect runs when one of the dependencies changes. An empty array runs it only once after mount.
Example Code
useEffect(() => {
console.log('Runs on count change');
}, [count]);42. How does the dependency array in useEffect work?
Difficulty: MediumType: SubjectiveTopic: useEffect
React compares each dependency value on re-render. If any value changes, the effect re-runs. This helps control when side effects occur and avoid unnecessary work.
43. What are the rules that must be followed while using Hooks?
Difficulty: MediumType: SubjectiveTopic: Hooks
Hooks must be called at the top level of a component or custom hook, not inside loops, conditions, or nested functions. They must only be called inside React functions.
44. What is the purpose of useRef() hook?
Difficulty: MediumType: SubjectiveTopic: Refs
useRef() creates a mutable reference that persists across renders. It is commonly used to access DOM elements directly or store mutable values without causing re-renders.
Example Code
const inputRef = useRef(null);
<input ref={inputRef} />;45. What are the use cases of refs in functional components?
Difficulty: MediumType: SubjectiveTopic: Refs
Refs are used to access or modify DOM elements directly, store previous values, and hold data that doesn’t need to trigger re-renders.
46. Why do React Hooks make use of refs?
Difficulty: MediumType: SubjectiveTopic: Refs
Refs let Hooks store values that survive re-renders without updating the UI. This is useful for timers, external libraries, or manual DOM access.
47. What are custom hooks in React?
Difficulty: MediumType: SubjectiveTopic: Custom Hooks
Custom hooks are reusable functions that use React’s built-in hooks. They allow you to extract logic from components and reuse it across multiple components.
Example Code
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}48. When should you create a custom hook?
Difficulty: MediumType: SubjectiveTopic: Custom Hooks
Create a custom hook when you have reusable logic that involves React Hooks, like fetching data, handling input, or subscribing to events. It keeps your code clean and DRY.
49. What are the advantages of custom hooks?
Difficulty: MediumType: SubjectiveTopic: Custom Hooks
Custom hooks make logic reusable, easy to test, and separate UI from logic. They also simplify large components by organizing related logic together.
50. Which of the following manages side effects in functional components?
Difficulty: EasyType: MCQTopic: useEffect
- useEffect
- useState
- useMemo
- useRef
useEffect handles side effects like API calls or DOM updates after rendering. It is the Hook version of lifecycle methods.
Correct Answer: useEffect
51. What Hook is used for managing state in functional components?
Difficulty: EasyType: MCQTopic: State
- useClass
- useProps
- useState
- useContext
useState provides local state in functional components. It returns a value and a function to update it.
Correct Answer: useState
52. Which rule is true for Hooks?
Difficulty: MediumType: MCQTopic: Hooks
- Hooks can be used anywhere in code
- Hooks must be inside React components or custom hooks
- Hooks can be inside conditions
- Hooks must be inside classes
Hooks can only be called from functional components or other custom hooks, not from regular functions or class components.
Correct Answer: Hooks must be inside React components or custom hooks
53. What is prop drilling in React?
Difficulty: MediumType: SubjectiveTopic: Data Flow
Prop drilling happens when you pass data through many nested components just to reach a deeply nested child. It can make code harder to maintain and understand.
54. What are some ways to avoid prop drilling?
Difficulty: MediumType: SubjectiveTopic: Context
You can avoid prop drilling by using React Context API, Redux, Zustand, or custom hooks. These allow you to share data globally without passing props through multiple levels.
55. Explain the concept of context in React.
Difficulty: MediumType: SubjectiveTopic: Context
React Context allows data to be shared globally across components without passing props manually at every level. It is useful for themes, authentication, and global state.
Example Code
const ThemeContext = React.createContext('light');
<ThemeContext.Provider value='dark'><App/></ThemeContext.Provider>;56. How does React Context API help in managing global data?
Difficulty: MediumType: SubjectiveTopic: Context
Context API provides a Provider and Consumer pattern that lets you store and access global data. Components can subscribe to context updates directly, avoiding prop drilling.
57. What are Higher-Order Components (HOCs)?
Difficulty: MediumType: SubjectiveTopic: Patterns
A Higher-Order Component is a function that takes a component and returns a new component with extra functionality. It’s often used for cross-cutting concerns like logging or authentication.
Example Code
function withLogger(Wrapped) {
return function(props) {
console.log('Props:', props);
return <Wrapped {...props} />;
};
}58. Compare HOCs and custom hooks.
Difficulty: MediumType: SubjectiveTopic: Patterns
Both reuse logic across components. HOCs wrap components and add behavior, while custom hooks share logic using functions. Hooks are simpler and avoid nesting issues caused by HOCs.
59. What are render props in React?
Difficulty: MediumType: SubjectiveTopic: Patterns
Render props is a technique for sharing logic using a prop whose value is a function. The function returns UI based on data passed to it.
Example Code
<DataProvider render={(data) => <List items={data} />} />;60. What are error boundaries and how do they work?
Difficulty: MediumType: SubjectiveTopic: Error Bound
Error boundaries are React components that catch JavaScript errors in child components during rendering. They prevent entire app crashes by displaying fallback UIs.
61. How to implement an error boundary class?
Difficulty: MediumType: SubjectiveTopic: Error Bound
An error boundary is implemented using class components that define static getDerivedStateFromError() and componentDidCatch(). These catch and handle render errors.
Example Code
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() { return { hasError: true }; }
componentDidCatch(error, info) { console.log(error, info); }
render() { return this.state.hasError ? <h3>Error!</h3> : this.props.children; }
}62. In which lifecycle methods can you catch errors using an error boundary?
Difficulty: EasyType: SubjectiveTopic: Error Bound
Errors can be caught using getDerivedStateFromError and componentDidCatch lifecycle methods. These handle render-time errors gracefully.
63. What are fragments and why are they used?
Difficulty: EasyType: SubjectiveTopic: Fragments
Fragments let you group multiple elements without adding extra nodes to the DOM. They help keep your DOM clean and lightweight.
Example Code
<>
<h1>Title</h1>
<p>Content</p>
</>
64. What are portals in React?
Difficulty: MediumType: SubjectiveTopic: Portals
Portals let you render components outside the main DOM hierarchy, useful for modals or tooltips that need to escape parent overflow or z-index issues.
Example Code
ReactDOM.createPortal(<Modal />, document.getElementById('portal-root'));65. What is React reconciliation?
Difficulty: MediumType: SubjectiveTopic: Rendering
Reconciliation is React’s process of comparing Virtual DOM trees to decide which parts of the UI need to update. Only changed elements are re-rendered, improving performance.
66. How does React decide when to re-render a component?
Difficulty: MediumType: SubjectiveTopic: Rendering
React re-renders components when their state or props change. It uses a diffing algorithm to update only the affected parts of the DOM.
67. What are Pure Components and what is memoization (React.memo, useMemo, useCallback)?
Difficulty: MediumType: SubjectiveTopic: Performance
Pure Components and memoized functions skip re-renders when inputs don’t change. React.memo prevents re-rendering of functional components, useMemo caches computed values, and useCallback caches functions.
Example Code
const MemoComp = React.memo(MyComponent);
const memoValue = useMemo(() => computeExpensive(value), [value]);
const memoFn = useCallback(() => handleClick(id), [id]);
68. How to perform automatic redirect after login in React?
Difficulty: MediumType: SubjectiveTopic: Routing
In React Router v6, you can redirect users using the Navigate component after successful login. Once authentication succeeds, set a state like isLoggedIn to true and conditionally render <Navigate to='/dashboard' /> to send the user to the dashboard automatically.
Example Code
if (isLoggedIn) return <Navigate to='/dashboard' />;
else return <LoginForm />;
69. What is the difference between <Navigate> and <Redirect> in React Router?
Difficulty: MediumType: SubjectiveTopic: Routing
<Redirect> was used in React Router v5 for navigation. In React Router v6, it was replaced with <Navigate>. <Navigate> is a declarative way to redirect users to another route programmatically and is simpler to use with hooks and state.
Example Code
<Navigate to='/home' replace />
70. What are dynamic routes in React Router?
Difficulty: MediumType: SubjectiveTopic: Routing
Dynamic routes let you match variable segments in URLs, such as user IDs or product IDs. They are defined using a colon prefix like ':id', and React Router provides these values via the useParams() hook.
Example Code
<Route path='/user/:id' element={<UserProfile />} />;
const { id } = useParams();71. How do you handle route parameters and query strings?
Difficulty: MediumType: SubjectiveTopic: Routing
useParams() retrieves URL parameters like /user/:id, while useSearchParams() or URLSearchParams helps read query strings like ?sort=desc. These hooks simplify dynamic navigation and filtering in apps.
Example Code
const { id } = useParams();
const [query] = useSearchParams();
const sort = query.get('sort');72. How to protect private routes in React?
Difficulty: MediumType: SubjectiveTopic: Routing
Create a wrapper route that checks if the user is authenticated. If not, redirect them to login. This ensures only logged-in users can access certain pages.
Example Code
const PrivateRoute = ({ children }) => isAuth ? children : <Navigate to='/login' />;73. How can you optimize performance in a React app?
Difficulty: MediumType: SubjectiveTopic: Performance
React apps can be optimized by using memoization (React.memo, useMemo, useCallback), code-splitting, lazy loading, virtualization for lists, and avoiding unnecessary re-renders by properly managing dependencies and keys.
74. What causes unnecessary re-renders and how do you prevent them?
Difficulty: MediumType: SubjectiveTopic: Rendering
Unnecessary re-renders happen when state or props change unnecessarily, or when functions or objects are recreated each render. Prevent them using React.memo, useMemo, useCallback, and by avoiding direct mutations of state.
75. How does the key prop help React in render optimization?
Difficulty: EasyType: SubjectiveTopic: Lists Keys
Keys help React identify which elements changed, added, or removed in a list. This allows React to re-render only the modified items instead of the whole list, improving performance.
Example Code
{items.map(item => <li key={item.id}>{item.name}</li>)}76. What is code splitting and why is it useful?
Difficulty: MediumType: SubjectiveTopic: Code Split
Code splitting divides large bundles into smaller chunks, so only the code needed for a page loads. It reduces initial load time and improves app performance. It’s done using dynamic imports or React.lazy().
Example Code
const About = React.lazy(() => import('./About'));77. How do you implement lazy loading of components in React?
Difficulty: MediumType: SubjectiveTopic: Code Split
Use React.lazy() to load components only when needed, wrapped inside a <Suspense> fallback. This helps reduce bundle size and speeds up initial load.
Example Code
const Contact = React.lazy(() => import('./Contact'));
<Suspense fallback={<p>Loading...</p>}><Contact /></Suspense>78. How do you manage global state in React (Redux, Zustand, Context API)?
Difficulty: MediumType: SubjectiveTopic: State Mgmt
Global state can be handled using Redux for predictable centralized state, Context API for lightweight shared state, or Zustand for simpler and faster store-based state management without boilerplate.
79. How do you handle API calls in React (Fetch, Axios, React Query)?
Difficulty: MediumType: SubjectiveTopic: API
Fetch and Axios are used for HTTP requests. React Query helps manage server state with caching, auto refetching, and error handling. Always handle loading and error states during fetch operations.
Example Code
useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(setData)
.catch(console.error);
}, []);80. How do you perform cleanup in async calls to avoid memory leaks?
Difficulty: MediumType: SubjectiveTopic: useEffect
When a component unmounts during an async call, you should cancel ongoing operations. This can be done with AbortController, cleanup functions in useEffect, or checking mounted flags before updating state.
Example Code
useEffect(() => {
const controller = new AbortController();
fetch('/api', { signal: controller.signal });
return () => controller.abort();
}, []);81. What are common security practices for React apps?
Difficulty: MediumType: SubjectiveTopic: Security
Use proper input validation to prevent XSS, avoid dangerouslySetInnerHTML, use HTTPS, manage environment variables securely, and implement authentication with tokens or cookies properly.
82. How do you handle forms and validation in React?
Difficulty: MediumType: SubjectiveTopic: Forms
Use controlled components to manage input values through React state. For validation, libraries like Formik, React Hook Form, or Yup help manage form state, validation, and submission easily.
83. Which command creates a new React app?
Difficulty: EasyType: MCQTopic: Project Setup
- npm install create-react-app
- install -g create-react-app
- npm install -g create-react-app
- None of the above
The command 'npm install -g create-react-app' globally installs the tool for creating new React projects quickly.
Correct Answer: npm install -g create-react-app
84. Which of the following is an advantage of React?
Difficulty: EasyType: MCQTopic: React Basics
- Easier integration with other frameworks
- Increased performance via Virtual DOM
- Can render on server and client
- All of the above
React is flexible, integrates easily, supports SSR, and offers performance benefits with Virtual DOM.
Correct Answer: All of the above
85. What does the “webpack” command do?
Difficulty: EasyType: MCQTopic: Project Setup
- Runs React local development server
- Transpiles JavaScript
- Module bundler
- None of the above
Webpack is a module bundler that compiles and optimizes JavaScript, CSS, and assets into one or more bundles for production use.
Correct Answer: Module bundler
86. Step-by-step: How to create a React app using create-react-app or Vite?
Difficulty: EasyType: SubjectiveTopic: Project Setup
You can create a new React project using Create React App or Vite. For CRA, run `npx create-react-app my-app`, then `cd my-app` and `npm start`. For Vite, run `npm create vite@latest my-app -- --template react`, install dependencies, and start with `npm run dev`. Both provide an optimized development setup with hot reload and bundling.
Example Code
npx create-react-app my-app
# or
npm create vite@latest my-app -- --template react
87. What files and folders are generated in a new React project?
Difficulty: EasyType: SubjectiveTopic: Project Setup
A typical React app contains `src` for code, `public` for static assets, `package.json` for dependencies, `node_modules` for installed packages, and configuration files like `.gitignore` and `README.md`. Inside `src`, you’ll find `index.js` and `App.js` as entry points.
88. What is the purpose of package.json and dependencies in a React app?
Difficulty: EasyType: SubjectiveTopic: Project Setup
package.json lists your app’s metadata, scripts, and dependencies. It tells npm which libraries to install and how to run build or start commands. Dependencies are runtime libraries; devDependencies are for development tools like ESLint or Webpack.
89. How does JSX get compiled to JavaScript under the hood?
Difficulty: MediumType: SubjectiveTopic: JSX
JSX isn’t understood by browsers directly. The build tool (Babel) transpiles JSX into `React.createElement()` calls that produce virtual DOM objects. This keeps code readable while still working with standard JavaScript.
Example Code
<div>Hello</div> ➜ React.createElement('div', null, 'Hello')90. How to structure React components and folder hierarchy for a real project?
Difficulty: MediumType: SubjectiveTopic: Project Setup
Group code by feature: `components/`, `pages/`, `hooks/`, `context/`, `services/`, and `assets/`. Keep reusable components separate and avoid deep nesting. Use index.js barrels for cleaner imports.
91. What is the use of index.js and App.js?
Difficulty: EasyType: SubjectiveTopic: Project Setup
`index.js` is the main entry that renders the root component into the DOM using `ReactDOM.createRoot`. `App.js` is the top-level component where you compose routes and layout.
Example Code
ReactDOM.createRoot(document.getElementById('root')).render(<App />);92. Create a simple React Hooks example with useState and useEffect.
Difficulty: MediumType: SubjectiveTopic: Hooks
useState manages component state; useEffect runs side effects after render. For example, updating the document title when count changes.
Example Code
function Counter(){
const [count,setCount]=useState(0);
useEffect(()=>{document.title=`Count ${count}`;},[count]);
return <button onClick={()=>setCount(count+1)}>Add</button>;
}93. How to implement a search filter using state and controlled inputs?
Difficulty: MediumType: SubjectiveTopic: Forms
Keep the input value in state and filter a list based on it. Controlled inputs keep the displayed value in sync with React state, enabling instant updates and validation.
Example Code
const [search,setSearch]=useState('');
const filtered=data.filter(i=>i.name.includes(search));94. How to implement form validation using custom hooks?
Difficulty: MediumType: SubjectiveTopic: Forms
A custom hook like `useForm` can manage form state and validation logic. It tracks values, errors, and touched fields. You can combine it with Yup for schema-based validation.
95. How to manage localStorage or sessionStorage with hooks?
Difficulty: MediumType: SubjectiveTopic: API
You can build a custom hook that syncs state with localStorage. Whenever state changes, save it to storage and initialize from storage on load.
Example Code
function useLocal(key,init){
const [val,setVal]=useState(()=>JSON.parse(localStorage.getItem(key))||init);
useEffect(()=>localStorage.setItem(key,JSON.stringify(val)),[val]);
return [val,setVal];
}96. How to integrate APIs (fetch or axios) in functional components?
Difficulty: MediumType: SubjectiveTopic: API
Call the API inside useEffect after the first render, update state with results, and handle errors gracefully. Axios simplifies HTTP requests and error handling.
Example Code
useEffect(()=>{axios.get('/api').then(r=>setData(r.data)).catch(e=>setError(e));},[]);97. How to handle loading and error states during API calls?
Difficulty: MediumType: SubjectiveTopic: API
Use three pieces of state: data, loading, and error. Set loading true before fetch, update data on success, and show fallback UI on error.
Example Code
if(loading)return <p>Loading...</p>;
if(error)return <p>Error!</p>;
return <DataList data={data}/>;98. How to display lists of data using keys and components?
Difficulty: EasyType: SubjectiveTopic: Lists Keys
Map over an array and render a child component for each item. Provide a unique key prop to help React track changes efficiently.
Example Code
{users.map(u=><UserCard key={u.id} user={u}/>)}99. What function renders React content into an HTML page?
Difficulty: EasyType: MCQTopic: ReactDOM
- React.render()
- ReactDOM.start()
- React.mount()
- ReactDOM.render()
ReactDOM.render() (or createRoot in v18) mounts your root component into the DOM at the specified element ID.
Correct Answer: ReactDOM.render()
100. How can you pass data between React components (parent → child and child → parent)?
Difficulty: MediumType: SubjectiveTopic: Data Flow
Pass data from parent to child via props. To send data back up, pass a callback function from the parent and invoke it in the child with new data.
Example Code
// Parent
<Child onSave={setValue} />
// Child
props.onSave('updated');101. How can you create a functional component that returns a static layout using JSX?
Difficulty: EasyType: SubjectiveTopic: Static Layout
Simply return JSX markup from a function. For static content, you don’t need state or hooks.
Example Code
function Table(){ return (<table><tr><td>No data</td></tr></table>); }102. How would you import and use a custom component (e.g., SearchItem) in App.js?
Difficulty: EasyType: SubjectiveTopic: Components
Use ES module import syntax and include the component in JSX. Ensure it’s exported from its file with `export default SearchItem`.
Example Code
import SearchItem from './SearchItem';
function App(){ return <SearchItem/>; }103. What does the npm start command do in a React project?
Difficulty: EasyType: SubjectiveTopic: Project Setup
It runs the development server (using Vite or webpack-dev-server) and auto-reloads on code changes, serving the app at localhost.
104. What is conditional rendering in React and how is it implemented?
Difficulty: MediumType: SubjectiveTopic: Conditional UI
Conditional rendering shows components based on state or props conditions using ternaries or logical AND operators.
Example Code
{isLoggedIn ? <Dashboard/> : <Login/>}105. How does conditional rendering relate to authentication or permissions?
Difficulty: MediumType: SubjectiveTopic: Conditional UI
Auth-based apps show different UI for logged-in users. Conditional rendering hides private components until the user is authenticated.
106. Can React Hooks replace Redux for global state management?
Difficulty: MediumType: SubjectiveTopic: State Mgmt
For small apps, Context and Hooks can replace Redux. For large apps with complex state flows and middleware needs, Redux remains better suited.
107. Do React Hooks cover all class component functionalities?
Difficulty: MediumType: SubjectiveTopic: Hooks
Hooks cover most features like state and lifecycle methods, but error boundaries and getSnapshotBeforeUpdate still require classes.
108. How does the performance of Hooks compare to class components?
Difficulty: MediumType: SubjectiveTopic: Performance
Hooks are lightweight and reduce boilerplate, but improper use of effects can cause extra renders. With memoization, they perform equally or better.
109. Differentiate React Hooks and Classes in syntax and behavior.
Difficulty: MediumType: SubjectiveTopic: Hooks
Hooks use functions and closures for state and lifecycle, while classes use `this.state` and methods. Hooks allow logic reuse and simpler composition.
110. What are lifecycle methods in React and why are they useful?
Difficulty: MediumType: SubjectiveTopic: Lifecycle
Lifecycle methods manage setup and cleanup during a component’s life. Examples include componentDidMount, componentDidUpdate, and componentWillUnmount. Hooks like useEffect replace these.
111. What are the different phases of the React component lifecycle?
Difficulty: MediumType: SubjectiveTopic: Lifecycle
There are three phases: mounting (render and init), updating (re-render on changes), and unmounting (cleanup). React handles each phase internally.
112. What are some techniques to optimize React app performance?
Difficulty: MediumType: SubjectiveTopic: Performance
Use React.memo, useCallback, useMemo to avoid unnecessary renders. Code-split with React.lazy, lazy-load images, and virtualize long lists with react-window.
113. What are the different ways to style React components?
Difficulty: EasyType: SubjectiveTopic: Styling
You can style components using CSS modules, styled-components, inline styles, Tailwind, or plain CSS files. CSS modules and styled-components keep styles scoped.
114. How can you prevent unnecessary re-renders in React?
Difficulty: MediumType: SubjectiveTopic: Performance
Wrap components in React.memo, memoize functions and values, and avoid passing new objects or inline functions on every render.
115. What are Higher-Order Components (HOCs) and when are they needed?
Difficulty: MediumType: SubjectiveTopic: Patterns
HOCs are wrapper functions that add logic or data to a component. They’re useful for features like authentication, theming, or analytics.
116. What is StrictMode in React and what does it help detect?
Difficulty: EasyType: SubjectiveTopic: Strict Mode
StrictMode is a tool that activates extra checks in development. It detects unsafe lifecycle methods, side-effect bugs, and deprecated APIs.
117. How can you declaratively render a dynamic list of components based on an array?
Difficulty: EasyType: MCQTopic: Lists Keys
- Using <Each/>
- Using reduce()
- Using Array.map()
- Using loop
React recommends rendering lists using Array.map() because it produces a predictable array of JSX elements.
Correct Answer: Using Array.map()