Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
32 views12 pages

React

The document provides a comprehensive overview of React and its ecosystem, including setup, lifecycle, state management, and component types. It explains the differences between various tools like ESBuild and Rollup, as well as state management solutions such as Context API and Redux. Key concepts such as Virtual DOM, one-way data binding, and higher-order components are also discussed, highlighting React's unique features and performance optimizations.

Uploaded by

rootworld1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views12 pages

React

The document provides a comprehensive overview of React and its ecosystem, including setup, lifecycle, state management, and component types. It explains the differences between various tools like ESBuild and Rollup, as well as state management solutions such as Context API and Redux. Key concepts such as Virtual DOM, one-way data binding, and higher-order components are also discussed, highlighting React's unique features and performance optimizations.

Uploaded by

rootworld1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

1) How to setup your react+tailwind+

2) What happen when you run react app?


 When I run npm run dev in a Vite + React project

Dev server starts


 Node reads your package.json scripts → runs the build tool (here Vite’s development
server).
 Vite uses ESBuild for super-fast dependency pre-bundling.
 It reads my entry file (usually main.jsx), resolves imports, and transforms JSX →
JavaScript using Babel/ESBuild.
 Instead of creating a single big bundle like Webpack, Vite serves modules on demand
using native ES Modules in the browser.
 The dev server hosts your app on http://localhost:3000 (CRA) or 5173 (Vite).

Browser Loads and Runs Your App


 When I open the url, browser requests index.html
 Vite serves index.html directly (not bundled).
 This HTML includes <script type="module" src="/src/main.jsx"></script> — so the
browser requests my app code as an ES Module.

On-demand transformation & HMR (Hot Module Replacement)


 When the browser requests a file, Vite transforms it (JSX → JS, CSS handling, etc.) just in
time and sends it.
 If I change a file, Vite sends only that updated module via Hot Module Replacement
(HMR) without a full reload.

React mounts
 In main.jsx, ReactDOM.createRoot(document.getElementById("root")).render(<App />)
mounts the app into the #root div in index.html.
 React builds the Virtual DOM for <App />.
 React compares it with an empty DOM (since nothing is rendered yet) and updates the
real DOM
 React builds the Virtual DOM, diffs it, and updates the real DOM to show the UI.

3) Suppose browser request a bigfile with 100 imports how dev server(using vite)?
 Vite immediately transforms bigFile.jsx → plain JavaScript:
JSX → JS using ESBuild/Babel.
Rewrites import paths to absolute paths so the browser can request them individually.
Handles CSS imports (turns them into JS that injects <style> tags when loaded).
For asset imports (like images), it returns the correct dev URL.

Vite does not bundle all imports immediately. Instead, it sends the transformed bigFile.jsx
back to the browser with those imports still in place as import statements.

Because type="module" uses native ES Modules, the browser itself now sends separate
requests to Vite for each of the 100 imported files.
For each file:
Vite transforms it on demand (if not already cached in memory).
Returns it to the browser.

4) Why in production on demand file giving to browser is a bottlenect?


 In production, Vite bundles everything using Rollup bundler so users get fewer requests and
minified code.
If we used dev-style on-demand serving, the browser would make hundreds of requests and
parse unoptimized source code, which would be slow.
Production bundling ensures:
Fewer HTTP requests.
Minified, tree-shaken code.
Better caching.

5) Difference b/w esbuild and rollup bundlers in vite?


 ESBuild and Rollup are both bundlers, but they excel in different areas.
ESBuild is extremely fast because it’s written in Go and designed for quick builds, so Vite
uses it in dev mode to pre-bundle dependencies for instant startup and hot updates.

Rollup is slower but produces highly optimized output, so Vite uses it in production to
generate the final minified, tree-shaken, and code-split bundle.

6) What are features of React?


 Virtual Dom:-
React uses a Virtual DOM to track changes in the UI. Instead of updating the entire
DOM, React efficiently updates only the parts that changed. This makes rendering faster
and more efficient.

Unidirectional Data Flow:-


Data flows in a single direction (parent → child).Makes state changes and UI updates
more predictable.
CSR:-
React uses CSR which is usually faster after the first page.CSR apps behave like
native apps—instant routing, transitions.SSR apps need a full reload or hydration, which can
be slower.

Reusuable components:-
one break the UI into reusable components (e.g., Navbar, Card, Button). Each
component manages its own logic and rendering. Encourages modular and maintainable
code.

7) What is Dom and virtual Dom and where Virtual Dom is stored in react?
 The DOM is a tree-like structure created by the browser to represent the structure of HTML
page. JavaScript uses the DOM to read and manipulate web pages (e.g.,
document.getElementById, innerText, etc.).
Every change (like updating text or style) requires recalculating layout, repainting, and
reflow, which can be performance heavy.

The Virtual DOM (VDOM) is a lightweight JavaScript copy of the real DOM. React uses it to
improve performance.
The Virtual DOM is stored in browser’s memory — inside React's internal structures.
It's not visible in the browser’s DevTools.

8) How Virtual DOM works:


I) React renders the UI into a Virtual DOM (in memory).
II) When data changes, a new VDOM is created.
III)React diffs the new VDOM with the old one.
IV) Only the actual changed parts are updated in the real DOM — this process is called
reconciliation.

9) What is react Fibre?


 React Fiber is the new reconciliation engine introduced by the React team starting from
React 16.
Before Fiber, React's rendering process was synchronous and blocking. That meant if a
component tree was large, rendering it would block the main thread — making your app feel
sluggish or frozen during complex updates.
React Fiber is a reimplementation of the core algorithm in React for rendering and
reconciling components. It introduces incremental rendering, which means React can pause
work and come back to it later — enabling smoother user experiences.

Features of react fibre->


Incremental Rendering (Time Slicing)
React can split rendering work into chunks and spread it over multiple
frames.Helps with responsive UIs and avoids janky updates.
Prioritization
Fiber assigns priority levels to updates. For example, user interactions are
high-priority, while background data fetching is lower.Higher-priority
updates can interrupt lower-priority ones.
Concurrency (aka concurrent mode)
React can work on multiple updates simultaneously, improving
responsiveness.Enables features like Suspense, Transitions, and Streaming
SSR.
Backwards Compatibility
Though the underlying engine was rewritten, the public React API (like
useState, setState) didn’t change — so apps continued to work without
breaking.

10) Is react one way data binding or two way data binding?
 One-way data binding means data flows in one direction:
From the parent component (state/props) → to the child component.
If a child needs to change the data, it can’t change the parent’s state directly. Instead, it
must use a callback function passed as a prop from the parent.

React uses one way binding.

Angular/vue js uses two way data binding.

11) What is prop drilling?


 Prop drilling refers to the process of passing data (props) from a top-level component to
deeply nested child components, even if some intermediate components don’t need the
data themselves, but just pass it along.

🚨 Why it’s a problem?


Clutters intermediate components with unnecessary props.
Makes the code harder to maintain and understand.
Changes to the prop may require updates in all intermediate components.

Solution is-> use react context api, or some state management library.

12) What is difference b/w state and props?

 Feature State Props

Internal data owned by the External data passed to the


 Definition
component component

❌ Immutable (cannot be
✅ Mutable (can be changed
 Mutability modified by the receiving
using setState or useState)
component)

 Who Controlled by the Controlled by the parent


controls it? component itself component

To store and manage local


 Usage To receive data from parent
data

 Accessed this.state (class) or useState this.props (class) or directly via


with (hooks) props (hooks)

 Can be Yes, using setState or setX in


No, read-only in the child
updated? hooks

Form inputs, UI toggles, API Passing username to a Profile


 Example use
data component

13) How data is passed from child to parent component?


 The parent:
i) Defines a function
ii) Passes it to the child as a prop
iii) The child calls that function, optionally passing data

14) What are keys?


 A key is a unique identifier for each item in a list of elements, used by React to:
Efficiently track and update DOM elements.
Detect changes, insertions, and deletions in a list.
Avoid unnecessary re-renders.

React uses a diffing algorithm to compare the previous virtual DOM with the new one.
Without keys, React can get confused when items are reordered or updated.

Example->
const users = ["Alice", "Bob", "Charlie"];

return (
<ul>
{users.map((user, index) => (
<li key={user}>{user}</li> // key = unique value
))}
</ul>
);
No key or using index as a key give warning, as react doesn’t differ list of items. And index
is used as key when the list is static.

15) What are react contemporaries?


 React’s contemporaries are other JavaScript UI libraries or frameworks that are used to build
interactive frontends, just like React. For example Angular, vue etc.

Angular does not use a virtual dom instead, it directly manipulates the real dom and relies
on its change detection mechanism to efficiently update the user interface.
But react and vue utilize virtual dom as an in-memory representation to optimize updates by
diffing.

16) Is react library or framework?


 React is library focused only on building UI components. Not opinionated about routing,
state management, or data fetching.

A library provides specific functionality (like UI rendering) and is called by your code.
we’re in control of the flow to choose other tools.

A framework is a complete solution that often:


Controls the flow of your app (Inversion of Control).
Provides structure for routing, state, build tools, etc.
Example: Angular is a full-fledged framework.

17) What are higher order components?


 A Higher-Order Component (HOC) is an advanced pattern in React — it's a function that
takes a component and returns a new enhanced component.

Example: Logging Props HOC->


function withLogger(WrappedComponent) {
return function Enhanced(props) {
console.log("Props:", props);
return <WrappedComponent {...props} />;
};
}

Usage->
const MyComponentWithLogger = withLogger(MyComponent);

18) what is the difference b/w class component and functional component?
 Class Components:
Syntax: Defined as ES6 classes that extend React.Component.
State Management: Manage internal state using this.state and update it with this.setState().
Lifecycle Methods: Provide access to various lifecycle methods (e.g., componentDidMount,
componentDidUpdate, componentWillUnmount) for managing side effects and component
behavior at different stages.
render() Method: Require a render() method to return the JSX that describes the UI.
this Keyword: Extensive use of the this keyword to access props, state, and methods.

Functional Components:
Syntax:
Defined as plain JavaScript functions that accept props as an argument and return JSX.
State Management:
Manage state using React Hooks, primarily useState(), which allows functional components
to have their own local state.
Lifecycle Handling:
Handle side effects and lifecycle-like behavior using Hooks like useEffect(), which can
replicate the functionality of various class component lifecycle methods.
No render() Method:
Directly return JSX from the function body.
No this Keyword:
Do not use the this keyword; props are accessed directly as function arguments.

19) Life cycle methods of functional in react?


 All lifecycle behavior is handled using the useEffect() hook.

useEffect(() => {
// runs when component mounts and/or updates

return () => {
// cleanup: runs when component unmounts
};
}, [dependencies]);

Equivalent with
Lifecycle Phase When it runs
Hooks

Mount useEffect(() => {...}, Only once after the first


Equivalent with
Lifecycle Phase When it runs
Hooks

(componentDidMount) []) render

Update useEffect(() => {...}, Every time dependency


(componentDidUpdate) [dependency]) changes

Cleanup function runs


Unmount return () => {...}
when component
(componentWillUnmount) inside useEffect()
unmounts

20) What if I pass null in the 2nd parameter as null in UseEffect?


 UseEffect hook take two parameter 1) callback function 2) dependency array
now If we pass 2nd parameter is null then it give runtime error.
"Cannot read properties of null (reading 'includes')"

21) What are fragments in react?


 In React, a Fragment is a special component that lets you group multiple elements without
adding extra nodes to the DOM.

return (
<div>
<h1>Hello</h1>
<p>Welcome</p>
</div>
);

here this adds an unnecessary <div> node to the DOM.

instead of this use <></> or <React.Fragment></React.Fragment> just like below,


return (
<React.Fragment>
<h1>Hello</h1>
<p>Welcome</p>
</React.Fragment>
);

22) What is stateless and stateful components ?


 A stateless component is a component that:
Does not manage any internal state
Receives data via props
Focuses on UI rendering only

A stateful component is ->


Manages its own internal state, Can handle logic, events, and side effects,
may pass data down to child components
23) Is useState synchronous?
 When one call setState (like setCount(5)), React does not update the state immediately.
The new state will be available on the next render cycle, not immediately.

So useState is asynchronous.

const [count, setCount] = useState(0);


setCount(5);
console.log(count); / / ❌ Still 0, not 5

24) Make a comparison b/w useReducer and useState hook?


 UseState is used for simple , independent state variable , easy updates like toggles, counters,
inputs.

UseReducer is used for complex state logic, multiple related state values, state depends on
previous state, alternative to redux for local state.

function Counter() {
const initialState = { count: 0 };

function reducer(state, action) {


switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
return state;
}
}

const [state, dispatch] = useReducer(reducer, initialState);

return (
<>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
</>
);
}

25) Difference b/w context api and redux?


 Context API:
Built-in: It's a native feature of React, so no additional libraries are required.
Scope: Ideal for lightweight, global state — like theme toggling, authentication
status, language preferences, etc.
Setup: Very minimal. You create a context, wrap your component tree in a provider,
and consume it with useContext.
Performance: Not optimized for high-frequency state updates. Re-renders the entire
subtree of the context provider, which can lead to performance issues for large
apps.
Debugging: Lacks devtools like Redux, so debugging large state flows is harder.

Redux:
External library: You need to install Redux and often use @reduxjs/toolkit for better
experience.
Scope: Suited for complex applications with a large amount of shared and
structured state (e.g., e-commerce carts, real-time dashboards, etc.).
Setup: More boilerplate. You define slices/reducers, actions, a store, and use
providers/hooks to connect everything.
Performance: More optimized and predictable with powerful middleware support
like redux-thunk or redux-saga.
Debugging: Comes with advanced devtools for time-travel debugging and state
inspection, making it great for larger teams and scalable apps.

26) UseState and UseRef?

Why useState
 Situation Why useRef Works
Fails

Inside setInterval or Captures stale Holds mutable current


setTimeout state value

High-frequency updates (e.g., Triggers too many No re-render — perfect


scroll, mouse move) re-renders for performance

useState can't do
DOM element access useRef can access directly
it

function TimerWrong() {
const [seconds, setSeconds] = useState(0);

useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds + 1); // ❌ `seconds` always 0 due to stale closure here we’ve to use
//useref
}, 1000);
return () => clearInterval(interval);
}, []); // empty dependency, so `seconds` stays 0

return <p>Seconds: {seconds}</p>;


}

27) What is the role of index.html in react?


 In a React project (like one created with Vite, Create React App, or Next.js), the index.html
file serves as the single HTML entry point for entire frontend application.
1. Holds the root element (<div id="root">)
<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>My React App</title>
</head>
<body>
<div id="root"></div> <!-- React mounts the app here -->
</body>
</html>

2. React renders your app into this <div> into main.jsx.


import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));


root.render(<App />);

28) How react enables code splitting?


 React enables code splitting via dynamic import() and React.lazy().

🧩 Without Code Splitting:

import About from './About'; // loaded even if not used immediately


<Route path="/about" element={<About />} />

This will include About component in the initial bundle.

✅ With Code Splitting:

import React, { Suspense, lazy } from 'react';


const About = lazy(() => import('./About'));

<Route
path="/about"
element={
<Suspense fallback={<div>Loading...</div>}>
<About />
</Suspense>
}
/>

React.lazy() loads About only when the route is visited.


Suspense shows a fallback UI while the component loads.

29) How memo helps in optimisation?


 In react if parent re-renders, all of it’s children re-render by default even if props of children
looks same. So React still re-renders components before the diffing step happens, unless
you tell it not to do it. Here memo comes into picture.

React.memo is a higher-order component that memoizes a functional component , prevents


re-rendering of the component if its props haven’t changed.
Ex:-

const Child = React.memo(({ name }) => {


console.log("Child re-rendered");
return <p>Hello, {name}</p>;
});

function Parent() {
const [count, setCount] = useState(0);

return (
<>
<button onClick={() => setCount(count + 1)}>+</button>
<Child name="Nikhil" />
</>
);
}

Clicking the button changes the count, but Child doesn't re-render, because its prop
(name="Nikhil") didn't change. This is done by react.memo.
Without React.memo, it would re-render on every parent update.

30) What are the caveats of react.memo?


 Works only for props (not internal state).
Does a shallow comparison of props.
Be careful with functions/objects as props (they are new references each time — see
useCallback).

31) What is useCallback hook and how it helps in optimization?


 useCallback is a React Hook that memoizes a function, so that it doesn’t get recreated on
every render.
Useful when you're passing callbacks to memoized child components, to prevent
unnecessary re-renders.

Example without useCallback:->


const Child = React.memo(({ onClick }) => {
console.log("Child re-rendered");
return <button onClick={onClick}>Click Me</button>;
});

function Parent() {
const [count, setCount] = useState(0);
const handleClick = () => {
console.log("Button clicked");
};

return (
<>
<button onClick={() => setCount(count + 1)}>+</button>
<Child onClick={handleClick} />
</>
);
}

Even though handleClick doesn't change, it’s a new function every render, so Child re-
renders each time. So no meaning of using react.memo.

Now with useCallback:->

const handleClick = useCallback(() => {


console.log("Button clicked");
}, []); // will remain the same function unless dependencies change

Now Child receives the same function reference, so it doesn't re-render unnecessarily.

You might also like