是从https://www.geeksforgeeks.org/reactjs/react-interview-questions/获取的。
ReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. It is widely used by companies like Facebook, Instagram, Netflix, and Airbnb because of its flexibility and performance.
Key aspects of React are:
React.js works on a component-based architecture and uses a virtual DOM to efficiently update and render user interfaces.

{}.Example of JSX: The name written in curly braces { } signifies JSX
1const name = "Learner";2const element = (3 <h1>4 Hello,5 {name}.Welcome to GeeksforGeeks.6 </h1>7);Browsers can’t understand JSX directly. Instead, tools like Babel transpile it into plain JavaScript using React.createElement().
xxxxxxxxxx11const element = <h1>Hello, Geeks!</h1>;Babel converts it into:
xxxxxxxxxx11const element = React.createElement("h1", null, "Hello, World!");A Component is one of the core building blocks of React. In other words, we can say that every application you will develop in React will be made up of pieces called components. Components make the task of building UIs much easier.
In React, we mainly have two types of components:
| Functional Components | Class Components |
|---|---|
| A functional component is just a plain JavaScript pure function that accepts props as an argument | A class component requires you to extend from React. Component and create a render function |
| No render method used | It must have the render() method returning JSX |
| Also known as Stateless components | Also known as Stateful components |
| React lifecycle methods (for example, componentDidMount) cannot be used in functional components. | React lifecycle methods can be used inside class components (for example, componentDidMount). |
| Constructors are not used. | Constructor is used as it needs to store state. |
| Uses hooks like useState for managing state. | Uses this.state and this.setState for state management |
React allows us to pass information to a Component using something called props (which stands for properties). Props are objects which can be used inside a component. We can access any props inside from the component’s class to which the props is passed. The props can be accessed as shown below:
xxxxxxxxxx11this.props.propName;Default props are fallback values assigned to a component’s props when the parent does not provide them. They help prevent undefined errors and make components more robust. Default props can be defined using:
ComponentName.defaultProps = { propName: defaultValue }State is the internal, mutable data of a React component that controls its behavior and rendering. When state changes, React re-renders the component to update the UI.
State is updated using setState() in class components or the useState setter function in functional components. Updates are asynchronous and can be triggered by events, user interactions, or API responses. When new state depends on the previous state, the functional form (setState(prev => ...)) should be used.
| PROPS | STATE |
|---|---|
| The Data is passed from one component to another. | The Data is passed within the component only. |
| It is Immutable (cannot be modified). | It is Mutable ( can be modified). |
| Props can be used with state and functional components. | The state can be used only with the state components/class component (Before 16.0). |
| Props are read-only. | The state is both read and write. |
Example: Passing a title or onClick handler to a button component. | Example: A counter value that increases when you click a button. |
In React, fragments allow you to group multiple elements without adding extra nodes to the DOM. Normally, returning multiple elements requires a wrapper like a <div>, which can create unnecessary DOM elements. Fragments solve this by letting you return multiple elements without extra wrappers.
<> </> (cannot use attributes).<React.Fragment> </React.Fragment> (can use key).| Controlled Components | Uncontrolled Components |
|---|---|
| The React state controls the form input value. | The DOM manages the input value. |
Every change in input updates the state via onChange. | React uses ref to access the current value when needed. |
| Provides full control over input data. | Less code, simpler for basic forms. |
| Useful for validation, conditional rendering, or complex forms. | Less control over validation and state management. |
React does not manage the form input’s state. Instead, the DOM itself keeps track of the input’s value. You can access the value when needed using refs
React.createRef() or useRef() to access the current value.Hooks are special functions in React that let you use state, lifecycle methods, and other React features in functional components, which were previously only available in class components.
Why introduced:
x1import React, { useState } from 'react';23function Counter() {4 const [count, setCount] = useState(0);5 return (6 <div>7 <p>{count}</p>8 <button onClick={() => setCount(count + 1)}>Increment</button>9 </div>10 );11}useState hook work?The useState hook allows you to add state to functional components. It returns a state variable and a setter function to update that state. When the state changes, React re-renders the component with the updated value.
Example:
xxxxxxxxxx121import { useState } from 'react';23function Counter() {4 const [count, setCount] = useState(0);56 return (7 <div>8 <p>Count: {count}</p>9 <button onClick={() => setCount(count + 1)}>Increment</button>10 </div>11 );12}In this example:
count is the current state value.setCount is the function used to update state.0 is the initial value when the component mounts. When setCount is called, React re-renders Counter with the new count value.useEffect is a React hook that allows functional components to perform side effects such as fetching data, setting up subscriptions, or directly manipulating the DOM. It runs after the component renders, ensuring the UI is updated first.
The dependency array controls when the effect runs:
[] : runs once after the component mounts (like componentDidMount).[dep1, dep2] : runs only when a dependency changes.useEffect can also return a cleanup function that runs on unmount or before the next effect, helping prevent memory leaks.
Example :
xxxxxxxxxx41useEffect(() => {2 console.log('Effect runs');3 return () => console.log('Cleanup runs');4}, [dependency]);useEffect and useLayoutEffect?| useEffect | useLayoutEffect |
|---|---|
| Runs after render and painting | Runs before painting, after DOM updates |
| Non-blocking | Blocking |
| Used for data fetching, subscriptions, timers | Used for reading layout, measuring DOM, or sync DOM updates |
| Safer for most side effects | Can slow rendering if heavy logic is used |
| Runs after every render by default (or based on dependency array) | Use when DOM measurements are needed before painting |
useContext hook and when should you use it?The useContext hook allows functional components to consume values from a React Context without passing props through every level of the component tree (avoiding “prop drilling”).
When to use it:
useReducer hook and when is it preferred over useState?The useReducer is a React hook used to manage complex state logic in functional components. It works similarly to Redux: you define a reducer function that takes the current state and an action, and returns a new state.
Example:
xxxxxxxxxx41const [state, dispatch] = useReducer(reducer, initialState);23// Example usage:4dispatch({ type: 'increment' });In this example:
state is the current state.dispatch is used to send actions to update the state.Preferred over useState when:
useRef hook and what are its common use cases?The useRef hook creates a mutable object that persists across renders without causing re-renders. It is commonly used to access DOM elements or store mutable values.
Example:
xxxxxxxxxx161import { useRef } from 'react';23function App() {4 const inputRef = useRef();56 const focusInput = () => {7 inputRef.current.focus();8 };910 return (11 <div>12 <input ref={inputRef} type="text" />13 <button onClick={focusInput}>Focus</button>14 </div>15 );16}In this example:
inputRef stores a reference to the input DOM node.inputRef.current.focus() focuses the input without re-rendering the component.Common use cases:
useMemo and useCallback?| useMemo | useCallback |
|---|---|
| Memoizes computed values | Memoizes functions |
| Returns the result of a function | Returns the function itself |
| Avoids expensive recalculations on re-render | Prevents re-creating functions on re-render |
| Improves performance by caching values | Improves performance by avoiding unnecessary renders |
| Key idea: caches value | Key idea: caches function |
Syntax: useMemo(() => computeValue(a, b), [a, b]) | Syntax: useCallback(() => handleClick(id), [id]) |
Custom hooks are reusable functions that let you extract and share logic between functional components. They are JavaScript functions whose names start with use and can call other hooks like useState or useEffect.
Example:
xxxxxxxxxx251import { useState, useEffect } from 'react';23function useFetch(url) {4 const [data, setData] = useState(null);5 const [loading, setLoading] = useState(true);67 useEffect(() => {8 fetch(url)9 .then(res => res.json())10 .then(data => {11 setData(data);12 setLoading(false);13 });14 }, [url]);1516 return { data, loading };17}1819// Usage in a component20function App() {21 const { data, loading } = useFetch('https://api.example.com/data');2223 if (loading) return <p>Loading...</p>;24 return <div>{JSON.stringify(data)}</div>;25}In this example, useFetch is a custom hook that fetches data from an API and manages loading state. The hook is reused in App to keep the component clean and separate the data-fetching logic.
Hooks in React must follow certain rules to work correctly. These rules ensure that React can track state and effects reliably and prevent unexpected bugs.
use, like useFetch or useForm.Why they are important:
useState and useEffect.State management refers to how an application handles and shares data across components. It ensures that the UI is updated correctly whenever the underlying data (state) changes. In React, state can be managed locally (inside components) or globally (shared across multiple components using context, Redux, Zustand, etc.).
| Local State | Global State |
|---|---|
| Data managed within a single component. | Data shared across multiple components. |
Controlled using useState or useReducer inside the component. | Managed using Context API, Redux, Zustand, etc. |
| Used for UI-related data like form inputs, modals, or toggles. | Used for app-wide data like authentication, user info, or theme |
There are several approaches and libraries for managing state in React and Next.js, depending on the scale and complexity of your application:
useState, useReducer, useContext – for local or small-scale state management.useSWR, React Query, or Server Actions for fetching and caching server data efficiently.Choosing between Redux and Context API depends on the size and complexity of your application:
Use Redux when:
Use Context API when:
| Client State | Server State |
|---|---|
| Managed locally in the app | Managed on backend/server |
Controlled by useState, useReducer, Context | Controlled via API or DB |
| Short-lived (browser session) | Persistent across sessions/users |
| Examples: form inputs, UI toggles | Examples: user data, product list |
The Context API in React is used to share data globally across components without prop drilling. It allows you to wrap components with a provider and access the shared value anywhere in the tree using useContext.createContext() : Creates a context.
Consumer.The useReducer hook in React plays an important role in state management when the logic for updating state is complex or involves multiple actions. Unlike useState, which is best for simple state updates, useReducer organizes state transitions using a reducer function, making the code more predictable and easier to maintain. It is especially useful in larger applications or when managing related pieces of state.
useState.dispatch triggers actions.Persistent state ensures that certain data remains available even after page reloads or across sessions. Common approaches include:
useState or useReducer together with useEffect to sync state with storage.In React, sometimes you need values that depend on other state or props. These values can be handled as derived state or computed state, but they work differently:
useMemo. Ensures data stays consistent without storing redundant state.Optimizing state updates ensures that components re-render only when necessary, improving performance in React applications:
In React, state updates are asynchronous, so you need to handle them carefully to ensure predictable results:
setState or the setter from useState) do not happen immediately.setState when the new state depends on the previous state:xxxxxxxxxx11setCount(prevCount => prevCount + 1);useReducer for predictable state transitions.useEffect) to react to changes in state asynchronously.The Virtual DOM (VDOM) is a lightweight, in-memory representation of the real DOM in the browser. Instead of updating the actual DOM directly, which can be slow and costly, React first updates the Virtual DOM when a component’s state or props change. React then compares the new Virtual DOM with the previous one using a process called diffing, identifies the minimum set of changes needed, and updates only those parts of the real DOM. This approach makes UI updates faster and more efficient by reducing unnecessary DOM manipulations. Key points:
Reconciliation in React is the process of comparing the new Virtual DOM with the previous one to determine what has changed. React then updates only the necessary parts of the real DOM, instead of re-rendering the entire UI. This approach improves performance, rendering speed, and efficiency, ensuring a smooth and responsive user experience. Key points:
React.memo help improve performance?React.memo is a higher-order component that prevents unnecessary re-renders of functional components. It re-renders a component only if its props have changed, which helps improve performance in components that render frequently or are part of large lists.
Example: If you have a large list of items and only one item changes, React.memo ensures that the other list items do not re-render, saving processing time and improving UI performance.
To improve performance in a slow React application, you can use several optimization techniques:
Code splitting and lazy loading are techniques used to improve performance by reducing the initial load time of a React application.
In React, this is often implemented with React.lazy and <Suspense>:
xxxxxxxxxx91const MyComponent = React.lazy(() => import('./MyComponent'));23function App() {4 return (5 <Suspense fallback={<div>Loading...</div>}>6 <MyComponent />7 </Suspense>8 );9}Optimizing a React application ensures faster rendering and better performance, especially for large or complex apps:
React.lazy and Suspense for on-demand loading.useCallback instead.Both Component and PureComponent are used to create class components, but they handle re-rendering differently:
setState is called, regardless of whether the state or props have changed.Components automatically re-render when their state or props change, but React optimizes this process using the virtual DOM:
Form inputs can be controlled or uncontrolled, and this affects how they are rendered and updated:
onChange.In React, re-renders can be expensive if functions or computed values are recreated unnecessarily. useMemo and useCallback help optimize rendering by caching values and functions:
In React, lists are usually rendered using JavaScript’s .map() method. Each list item should also have a unique key prop so React can efficiently track and update elements.
xxxxxxxxxx81const fruits = ["Apple", "Banana", "Mango"];2return (3 <ul>4 {fruits.map((fruit, index) => (5 <li key={index}>{fruit}</li>6 ))}7 </ul>8);In this Example, .map() is used to iterate over the array, and the key prop helps React identify each list item uniquely.
key prop important in React lists?The key prop is important because it helps React efficiently manage list rendering. It allows React to identify which items have changed, been added, or removed, instead of re-rendering the entire list.
Using the array index as a key technically works, but it is not recommended in most cases. If the list changes (items are reordered, added, or removed), React may reuse components incorrectly, leading to UI bugs.
In React, list items can be conditionally rendered using techniques like if statements, ternary operators, or array methods such as .filter() combined with .map().
Example:
xxxxxxxxxx81const users = [{name: "Aman", active: true}, {name: "Raj", active: false}];2return (3 <ul>4 {users5 .filter(user => user.active)6 .map(user => <li key={user.name}>{user.name}</li>)}7 </ul>8);State is immutable, so you cannot modify arrays directly. Instead, you create a new array using methods like .map() or .filter() and then update state with that new array.
Example (removing an item):
xxxxxxxxxx51const [list, setList] = useState(["A", "B", "C"]);23const removeItem = (item) => {4 setList(list.filter(i => i !== item));5};In this example, .filter() creates a new array without the removed item, and setList updates the state.
Rendering very large lists can hurt performance, so React provides techniques and best practices to optimize them:
react-window or react-virtualized to render only the visible portion of the list.React.memo to prevent unnecessary re-renders.You can nest .map() calls: one for the parent array and another for the child array.
Example:
xxxxxxxxxx191const categories = [2 { name: "Fruits", items: ["Apple", "Banana"] },3 { name: "Veggies", items: ["Carrot", "Tomato"] }4];56return (7 <div>8 {categories.map(cat => (9 <div key={cat.name}>10 <h3>{cat.name}</h3>11 <ul>12 {cat.items.map(item => (13 <li key={item}>{item}</li>14 ))}15 </ul>16 </div>17 ))}18 </div>19);In this example, each level of data gets its own .map() loop, and both parent and child elements should have unique key props.
In React, since state is immutable, you cannot directly modify the existing array. Instead, you create a new array that includes the new item and update state.
Example:
xxxxxxxxxx51const [list, setList] = useState(["A", "B"]);23const addItem = (item) => {4 setList([list, item]);5};In this example:
[...list, item] creates a new array with the existing items plus the new one.setList with this new array updates the state and triggers a re-render, showing the updated list in the UI.In React, lists are usually stored in state, and you can sort or filter them dynamically by creating a new array based on the original list and updating the state.
Example:
xxxxxxxxxx111const [users, setUsers] = useState([2 { name: "Aman", age: 25 },3 { name: "Raj", age: 30 },4 { name: "Sara", age: 22 }5]);67// Filter active users8const filteredUsers = users.filter(user => user.age > 24);910// Sort by name11const sortedUsers = [users].sort((a, b) => a.name.localeCompare(b.name));In this example:
filter creates a new array containing only the items that meet the condition.sort rearranges the array items; using [...users] ensures the original state is not mutated.When rendering lists, it’s important to return JSX elements for each item. The choice between map() and forEach() affects this:
Example using map():
xxxxxxxxxx61const fruits = ["Apple", "Banana", "Mango"];2return (3 <ul>4 {fruits.map(fruit => <li key={fruit}>{fruit}</li>)}5 </ul>6);In this example:
map returns an array of <li> elements, which React renders.forEach here would not work, because it does not return the array of elements.In plain HTML, the browser’s DOM manages form data. In React, form inputs are usually controlled components:
xxxxxxxxxx191function MyForm() {2 const [name, setName] = React.useState("");34 const handleSubmit = (e) => {5 e.preventDefault();6 alert("Submitted: " + name);7 };89 return (10 <form onSubmit={handleSubmit}>11 <input 12 type="text" 13 value={name} 14 onChange={(e) => setName(e.target.value)} 15 />16 <button type="submit">Submit</button>17 </form>18 );19}In this example, the input is fully controlled by React through value and onChange.
By using event.preventDefault() inside the form’s onSubmit handler.
Example:
xxxxxxxxxx41const handleSubmit = (e) => {2 e.preventDefault();3 console.log("Form submitted!");4};In this example, the page is stopped from reloading and lets React control what happens on submit.
event.stopPropagation().xxxxxxxxxx41const handleClick = (e) => {2 e.stopPropagation();3 console.log("Child clicked, but won’t bubble up.");4};By using a single state object and updating it dynamically with name and value.
Example:
xxxxxxxxxx51const [formData, setFormData] = useState({ name: "", email: "" });23const handleChange = (e) => {4 setFormData({ formData, [e.target.name]: e.target.value });5};This way, one handler can manage multiple inputs.
In React, form inputs are usually controlled components, meaning their values are stored in state. To reset a form, you simply reset the state that controls the inputs:
Example:
xxxxxxxxxx81const [formData, setFormData] = useState({ name: "", email: "" });23const handleSubmit = (e) => {4 e.preventDefault();5 console.log(formData);6 // Reset form fields7 setFormData({ name: "", email: "" });8};In this example:
setFormData({ name: "", email: "" }) resets all input fields to their initial values.React Router is a library that enables client-side routing in React applications. It allows you to create single-page applications (SPAs) where navigation between views happens without a full page reload, making apps faster and smoother.
<a> tag and <Link> in React Router?<a> tag: Reloads the whole page when navigating.<Link> component: Updates the URL and changes the component without reloading (SPA behavior).<BrowserRouter> – Wraps the app and enables routing.<Routes> – Container for all route definitions.<Route> – Defines a path and the component to render.<Link> / <NavLink> – For navigation.useNavigate() – For programmatic navigation.useHistory and useNavigate?useHistory().useNavigate().xxxxxxxxxx21const navigate = useNavigate(); 2navigate("/dashboard"); xxxxxxxxxx61<Routes>2 <Route path="/dashboard" element={<Dashboard />}>3 <Route path="profile" element={<Profile />} />4 <Route path="settings" element={<Settings />} />5 </Route>6</Routes>/dashboard/profile : shows Profile inside Dashboard.
Route params are dynamic parts of the URL.
xxxxxxxxxx11<Route path="/users/:id" element={<User />} />Inside User component:
xxxxxxxxxx21import { useParams } from "react-router-dom";2const { id } = useParams();/users/101 : id = 101
<Navigate> component:xxxxxxxxxx11<Route path="/old" element={<Navigate to="/new" />} />Using useNavigate() hook for programmatic redirects.
client-side routing and server-side routing?Client-Side Routing
Example Flow:
/about.index.html + JS bundle (React app)./about and loads <About /> component without reloading the page.Server-Side Routing
In server-side routing, whenever a user clicks a link or enters a URL:
Example Flow:
/about./about.about.html page.<Switch> and <Routes> in React RouterSwitch:
component, render, and children props.exact keyword to avoid unwanted matches.Example:
xxxxxxxxxx51<Switch>2 <Route exact path="/" component={Home} />3 <Route path="/about" component={About} />4 <Route path="/contact" render={() => <Contact />} />5</Switch>Routes:
<Switch>.element prop for rendering.<Switch>.exact keyword anymore.<Switch> is deprecated, and <Routes> is now the recommended way.Example:
xxxxxxxxxx51<Routes>2 <Route path="/" element={<Home />} />3 <Route path="/about" element={<About />} />4 <Route path="/contact" element={<Contact />} />5</Routes>
This React Interview Questions and Answers covers a wide range of topics, from basic concepts to advanced techniques. Whether you're a beginner or an experienced developer, mastering these questions will enhance your readiness for React interviews and boost your confidence.
This set contains the advanced-level questions asked in the interview.
Custom hooks are normal JavaScript functions whose names start with “use”, and they may call other hooks. We use custom hooks to maintain the DRY concept, which is Don't Repeat Yourself. It helps us to write a logic once and use it anywhere in the code. Some of the commonly used custom hooks are:
We can improve our React code by following these practices:
| Feature | useRef | createRef |
|---|---|---|
| Type | It is a type of hook. | It is a function. |
| Component Type | Used in functional components. | Used in class components. |
| Re-render Behavior | It saves its value between re-renders in a functional component. | It creates a new ref for every re-render. |
| Ref Value | Returns a mutable ref object ({ current: value }). | Returns a new ref object every time. |
| Use Cases | Storing DOM references, instance variables, and previous state values without re-renders. | Storing DOM references in class components. |
| Example | const ref = useRef(null); | this.ref = React.createRef(); |
React Redux is a state management tool which makes it easier to pass these states from one component to another irrespective of their position in the component tree and hence prevents the complexity of the application. As the number of components in our application increases it becomes difficult to pass state as props to multiple components. To overcome this situation we use react-redux.
There are several benefits of using react-redux such as
There are four fundamental concepts of redux in react which decide how the data will flow through components
When working with Redux we sometimes require multiple reducers. In many cases, multiple actions are needed, resulting in the requirement of multiple reducers. However, this can become problematic when creating the Redux store. To manage the multiple reducers we have function called combineReducers in the redux. This basically helps to combine multiple reducers into a single unit and use them.
Syntax
xxxxxxxxxx51import { combineReducers } from "redux";2const rootReducer = combineReducers({3 books: BooksReducer,4 activeBook: ActiveBook5});Context API is used to pass global variables anywhere in the code. It helps when there is a need for sharing state between a lot of nested components. It is light in weight and easier to use, to create a context just need to call React.createContext(). It eliminates the need to install other dependencies or third-party libraries like redux for state management. It has two properties Provider and Consumer.
A provider is used to provide context to the whole application whereas a consumer consume the context provided by nearest provider. In other words The Provider acts as a parent it passes the state to its children whereas the Consumer uses the state that has been passed.
In ReactJS, Cross-Origin Resource Sharing (CORS) refers to the method that allows you to make requests to the server deployed at a different domain. As a reference, if the frontend and backend are at two different domains, we need CORS there.
We can setup CORS evironment in frontend using two methods:
Axios, which is a popular library is mainly used to send asynchronous HTTP requests to REST endpoints. This library is very useful to perform CRUD operations.
To install aixos package in react use the following command.
xxxxxxxxxx11npm i axiosxxxxxxxxxx301import React, { useState } from "react";23const App = () => {4 const [counter, setCounter] = useState(0)5 const handleClick1 = () => {6 setCounter(counter + 1)7 }89 const handleClick2 = () => {10 setCounter(counter - 1)11 }1213 return (14 <div>15 <div>16 {counter}17 </div>18 <div className="buttons">19 <button onClick={handleClick1}>20 Increment21 </button>22 <button onClick={handleClick2}>23 Decrement24 </button>25 </div>26 </div>27 )28}2930export default AppOutput:

In this example
It is advised to use a callback-based approach to update the state using setState because it solves lots of bugs upfront that may occur in the future.We can use the following syntax to update the state using a callback.
xxxxxxxxxx61this.setState(st => {2 return(3 st.stateName1 = state1UpdatedValue,4 st.stateName2 = state2UpdatedValue5 )6})React Material UI is a framework built upon React library which contains predefined components to create React applications. Material UI is basically a design language built by Google in 2014 and works with various JavaScript frameworks apart from React such as Angular.js and Vue.js. The quality of the inbuilt designs of Material UI and its easy implementation make it the first choice of most developers. The inbuilt components are also customizable so it helps easily recreate the designs.
Flux is an architecture that Facebook uses internally when operating with React. It is merely a replacement quite an architecture that enhances React and also the idea of unidirectional data flow.
The useMemo is a hook used in the functional component of react that returns a memoized value. In Computer Science, memoization is a concept used in general when we don’t need to recompute the function with a given argument for the next time as it returns the cached result. A memoized function remembers the results of output for a given set of inputs.
React do not update immediately, although it seems immediate at first glance. React keep track of the states by queuing them in the order they are called. React queue all the changes to be made and update once the component Re-render which is not immediate. This is how React knows which value corresponds to which state. It goes as per the queue every time the component tries to re-render.
There are three types of routers in React:
The React StrictMode can be viewed as a helper component that allows developers to code efficiently and brings to their attention any suspicious code which might have been accidentally added to the application. The StrictMode can be applied to any section of the application, not necessarily to the entire application.
xxxxxxxxxx111import React from "react";2import ReactDOM from "react-dom/client";3import App from "./App";45const root = ReactDOM.createRoot(document.getElementById("root"));67root.render(8 <React.StrictMode>9 <App />10 </React.StrictMode>11);Conditional rendering in React means dynamically displaying components or elements based on a condition. Instead of rendering everything at once, React decides what to render based on the current state, props, or logic. We can use conditional rendering when:
React Router is a library for handling navigation in React applications. It allows developers to create single-page applications (SPAs) with multiple views while maintaining a smooth, seamless user experience without full-page reloads.
Let's now create the simple react router.
xxxxxxxxxx231// App.js2import React from "react";3import { BrowserRouter as Router, Route, Routes, Link } from "react-router-dom";45// Components for different pages6const Home = () => <h2>Home Page</h2>;7const About = () => <h2>About Page</h2>;89const App = () => {10 return (11 <Router>12 <nav>13 <Link to="/">Home</Link> | <Link to="/about">About</Link>14 </nav>15 <Routes>16 <Route path="/" element={<Home />} />17 <Route path="/about" element={<About />} />18 </Routes>19 </Router>20 );21};2223export default App;xxxxxxxxxx101//index.js2import React from "react";3import ReactDOM from "react-dom/client";4import App from "./App";56// Create a root element7const root = ReactDOM.createRoot(document.getElementById("root"));89// Render the App component10root.render(<App />);
Output

In this example
<App />) tells React to render the App component inside the root element created earlier.Note: React 18 introduces this new way of rendering the app. The createRoot() method is now used instead of the old render() method to improve performance and enable new features like concurrent rendering.
| Feature | React Hooks | Class Components |
|---|---|---|
| State Management | useState() hook for state handling. | this.state for state handling. |
| Reusability | Custom hooks allow sharing logic across components. | Inheritance is used for sharing logic, but it’s more complex. |
| this Keyword | No use of this. State and methods are directly accessible. | Uses this to access state and methods (this.state, this.setState()). |
| Lifecycle Methods | useEffect() for side effects and lifecycle management. | Methods like componentDidMount(), componentDidUpdate(), etc. |
| Performance | React's new hooks API has better performance optimizations. | Generally less efficient compared to functional components and hooks. |
In React, data is passed between components using props. The way data flows between components depends on whether they are parent-child, sibling components, or if you're using state management techniques like context or Redux.
Lazy Loading in React is a technique used to load components only when they are needed, instead of loading everything at once when the app starts. This helps improve the performance of the app by reducing the initial loading time. In React, React.lazy() is used to implement lazy loading for components, which allows you to split your code into smaller bundles and load them only when required.
Redux is a state management library that helps manage the application state globally. React-Redux is used to connect Redux state to React components. There are the three main components of the redux:
React Routing is used in Single Page Applications (SPAs), while conventional routing typically applies to multi-page applications. Here’s how they differ:
| Features | React Routing | Conventional Routing |
|---|---|---|
| Page Loading | No full page reload; components are dynamically rendered. | Entire page reload happens with every navigation. |
| SEO Considerations | React Router needs additional configurations (like SSR or dynamic rendering) to optimize SEO. | SEO is typically easier to manage since pages are fully rendered by the server. |
| Navigation | Navigation is handled by JavaScript on the client-side, often using Link and NavLink components. | Navigation is handled by the server through HTML anchor tags (). |
| Technology | Managed via React Router; uses client-side routing. | Managed by server-side routing (e.g., Express, PHP). |
| URL Structure | URLs can have dynamic parameters handled by React Router (e.g., /product/:id). | URLs are typically static and are managed by the server. |
In ReactJS, binding in the context of event handlers is often required to ensure that the correct this context is available inside class methods. However, it can lead to boilerplate code and performance issues, especially when binding functions in each render cycle. We can avoid binding in ReactJS by using the below methods:
In React, props (short for "properties") are a way of passing data from a parent component to a child component. Props are read-only and are used to customize or control the behavior of a component. They help make components reusable and dynamic by allowing different data to be passed into them.
CSS Modules help you keep your styles specific to each React component, so they don't affect other components. In simple terms, it lets you write CSS for one component without worrying about messing up the styles of other parts of your app. This is especially useful when your app grows larger and has many components, making it easier to manage styles without conflicts.
ReactJS is an essential JavaScript library for building dynamic, high-performance UIs with reusable components. Mastering advanced topics like custom hooks, Redux, performance optimization, and state management will help you excel in React job interviews and advance your career in 2025.