Skip to content

Commit 456e615

Browse files
committed
Update React core concepts
1 parent 2b9f8d5 commit 456e615

File tree

1 file changed

+175
-31
lines changed

1 file changed

+175
-31
lines changed

README.md

Lines changed: 175 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -996,28 +996,37 @@ class ParentComponent extends React.Component {
996996
997997
`SyntheticEvent` is a cross-browser wrapper around the browser's native event. Its API is same as the browser's native event, including `stopPropagation()` and `preventDefault()`, except the events work identically across all browsers. The native events can be accessed directly from synthetic events using `nativeEvent` attribute.
998998
999-
Let's take an example of BookStore title search component with the ability to get all native event properties
999+
Let's take an example of `BookStore` title search component with the ability to get all native event properties
10001000
10011001
```js
10021002
function BookStore() {
10031003
function handleTitleChange(e) {
10041004
console.log("The new title is:", e.target.value);
1005-
// 'e' represents synthetic event
1006-
const nativeEvent = e.nativeEvent;
1007-
console.log(nativeEvent);
1005+
console.log('Synthetic event:', e); // React SyntheticEvent
1006+
console.log('Native event:', e.nativeEvent); // Browser native event
10081007
e.stopPropagation();
10091008
e.preventDefault();
10101009
}
10111010

10121011
return <input name="title" onChange={handleTitleChange} />;
10131012
}
10141013
```
1014+
1015+
List of common synthetic events are:
1016+
1017+
* `onClick`
1018+
* `onChange`
1019+
* `onSubmit`
1020+
* `onKeyDown`, `onKeyUp`
1021+
* `onFocus`, `onBlur`
1022+
* `onMouseEnter`, `onMouseLeave`
1023+
* `onTouchStart`, `onTouchEnd`
10151024
10161025
**[⬆ Back to Top](#table-of-contents)**
10171026
10181027
14. ### What are inline conditional expressions?
10191028
1020-
You can use either _if statements_ or _ternary expressions_ which are available from JS to conditionally render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator `&&`.
1029+
You can use either _if statements_ or _ternary expressions_ which are available in JS(and JSX in React) to conditionally execute or render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator `&&`. It is helpful to render elements conditionally within a single line and commonly used for concise logic, especially in JSX rendering.
10211030
10221031
```jsx harmony
10231032
<h1>Hello!</h1>;
@@ -1049,6 +1058,10 @@ class ParentComponent extends React.Component {
10491058
<li key={index}>{todo.text}</li>
10501059
));
10511060
```
1061+
**Benefits of key:**
1062+
* Enables React to **efficiently update and re-render** components.
1063+
* Prevents unnecessary re-renders by **reusing** components when possible.
1064+
* Helps **maintain internal state** of list items correctly.
10521065

10531066
**Note:**
10541067

@@ -1062,53 +1075,71 @@ class ParentComponent extends React.Component {
10621075
10631076
16. ### What is Virtual DOM?
10641077
1065-
The _Virtual DOM_ (VDOM) is an in-memory representation of _Real DOM_. The representation of a UI is kept in memory and synced with the "real" DOM. It's a step that happens between the render function being called and the displaying of elements on the screen. This entire process is called _reconciliation_.
1078+
The _Virtual DOM_ (VDOM) is a lightweight, in-memory representation of _Real DOM_ used by libraries like React to optimize UI rendering. The representation of a UI is kept in memory and synced with the "real" DOM. It's a step that happens between the render function being called and the displaying of elements on the screen. This entire process is called _reconciliation_.
10661079

10671080
**[⬆ Back to Top](#table-of-contents)**
10681081

10691082
17. ### How Virtual DOM works?
10701083

1071-
The _Virtual DOM_ works in three simple steps.
1072-
1073-
1. Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.
1074-
1075-
![vdom](images/vdom1.png)
1076-
1077-
2. Then the difference between the previous DOM representation and the new one is calculated.
1084+
The _Virtual DOM_ works in five simple steps.
1085+
**1. Initial Render**
1086+
When a UI component renders for the first time, it returns JSX. React uses this structure to create a Virtual DOM tree, which is a lightweight copy of the actual DOM. This Virtual DOM is then used to build and render the Real DOM in the browser.
10781087

1079-
![vdom2](images/vdom2.png)
1088+
**2. State or Props Change**
1089+
When the component's state or props change, React creates a new Virtual DOM reflecting the updated UI. However, it doesn't immediately update the Real DOM; instead, it works in memory to prepare for an efficient update.
1090+
1091+
![vdom](images/vdom1.png)
10801092

1081-
3. Once the calculations are done, the real DOM will be updated with only the things that have actually changed.
1093+
**3. Diffing Algorithm**
1094+
React then compares the new Virtual DOM with the previous one using a process called diffing. It determines what has changed between the two versions and identifies the minimal set of updates needed.
1095+
1096+
![vdom2](images/vdom2.png)
10821097

1098+
**4. Reconciliation**
1099+
Based on the diffing results, React decides which parts of the Real DOM should be updated. It avoids re-rendering the entire DOM and instead updates only the elements that actually changed.
1100+
10831101
![vdom3](images/vdom3.png)
10841102

1103+
**5. Efficient DOM Updates**
1104+
This entire process—working with the Virtual DOM, diffing, and selective updating—makes the UI rendering much faster and more efficient than manipulating the Real DOM directly.
1105+
10851106
**[⬆ Back to Top](#table-of-contents)**
10861107

10871108
18. ### What is the difference between Shadow DOM and Virtual DOM?
10881109

10891110
The _Shadow DOM_ is a browser technology designed primarily for scoping variables and CSS in _web components_. The _Virtual DOM_ is a concept implemented by libraries in JavaScript on top of browser APIs.
10901111

1112+
The key differences in a table format shown below:
1113+
1114+
| Feature | Shadow DOM | Virtual DOM |
1115+
| --- | --- | --- |
1116+
| Purpose | Encapsulation for Web Components | Efficient UI rendering |
1117+
| Managed by | Browser | JS frameworks (e.g., React) |
1118+
| DOM Type | Part of real DOM (scoped) | In-memory representation |
1119+
| Encapsulation | Yes | No |
1120+
| Use Case | Web Components, scoped styling | UI diffing and minimal DOM updates |
1121+
10911122
**[⬆ Back to Top](#table-of-contents)**
10921123

10931124
19. ### What is React Fiber?
10941125

1095-
Fiber is the new _reconciliation_ engine or reimplementation of core algorithm in React v16. The goal of React Fiber is to increase its suitability for areas like animation, layout, gestures, ability to pause, abort, or reuse work and assign priority to different types of updates; and new concurrency primitives.
1126+
**React Fiber** is the **new reconciliation engine** in React, introduced in React 16. It’s a complete rewrite of React’s core algorithm(old stack-based algorithm) for rendering and updating the UI. Fiber enhances React’s ability to handle **asynchronous rendering**, **prioritized updates**(assign priority to different types of updates), and **interruption**(ability to pause, abort, or reuse work) of rendering work, enabling smoother and more responsive user interfaces.
10961127

10971128
**[⬆ Back to Top](#table-of-contents)**
10981129

10991130
20. ### What is the main goal of React Fiber?
11001131

11011132
The goal of _React Fiber_ is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is **incremental rendering**: the ability to split rendering work into chunks and spread it out over multiple frames.
11021133

1103-
_from documentation_
1104-
11051134
Its main goals are:
11061135

1107-
1. Ability to split interruptible work in chunks.
1108-
2. Ability to prioritize, rebase and reuse work in progress.
1109-
3. Ability to yield back and forth between parents and children to support layout in React.
1110-
4. Ability to return multiple elements from render().
1111-
5. Better support for error boundaries.
1136+
* **Incremental Rendering** – Breaks work into chunks for smoother updates.
1137+
* **Interruptible Rendering** – Pauses and resumes rendering to keep the UI responsive.
1138+
* **Prioritization** – Handles high-priority updates (e.g. animations) before low-priority ones.
1139+
* **Concurrency Support** – Enables working on multiple UI versions simultaneously.
1140+
* **Better Error Handling** – Supports component-level error boundaries.
1141+
* **Suspense Support** – Allows waiting for async data before rendering.
1142+
* **Improved DevTools** – Enables better debugging and performance tracking.
11121143

11131144
**[⬆ Back to Top](#table-of-contents)**
11141145

@@ -1236,9 +1267,31 @@ class ParentComponent extends React.Component {
12361267
**[⬆ Back to Top](#table-of-contents)**
12371268
12381269
23. ### What is the difference between createElement and cloneElement?
1270+
Both `React.createElement` and `React.cloneElement` are used to work with React elements, but they serve different purposes.
12391271
1240-
JSX elements will be transpiled to `React.createElement()` functions to create React elements which are going to be used for the object representation of UI. Whereas `cloneElement` is used to clone an element and pass it new props.
1272+
#### **createElement:**
1273+
Creates a new React element from scratch. JSX elements will be transpiled to `React.createElement()` functions to create React elements which are going to be used for the object representation of UI.
1274+
**Syntax:**
1275+
```jsx
1276+
React.createElement(type, props, ...children)
1277+
```
1278+
**Example:**
1279+
```jsx
1280+
React.createElement('button', { className: 'btn' }, 'Click Me')
1281+
```
1282+
#### **cloneElement:**
1283+
The `cloneElement` method is used to clone an existing React element and optionally adds or overrides props.
12411284
1285+
**Syntax:**
1286+
```jsx
1287+
React.cloneElement(element, newProps, ...children)
1288+
```
1289+
**Example:**
1290+
```jsx
1291+
const button = <button className="btn">Click Me</button>;
1292+
const cloned = React.cloneElement(button, { className: 'btn-primary' });
1293+
// Result: <button className="btn-primary">Click Me</button>
1294+
```
12421295
**[⬆ Back to Top](#table-of-contents)**
12431296
12441297
24. ### What is Lifting State Up in React?
@@ -1249,20 +1302,66 @@ class ParentComponent extends React.Component {
12491302
12501303
25. ### What are Higher-Order Components?
12511304
1252-
A _higher-order component_ (_HOC_) is a function that takes a component and returns a new component. Basically, it's a pattern that is derived from React's compositional nature.
1305+
A _higher-order component_ (_HOC_) is a function that takes a component and returns a new enhanced component with additional props, behavior, or data. It’s a design pattern based on Reacts compositional nature, allowing you to reuse logic across multiple components without modifying their internals.
12531306
1254-
We call them **pure components** because they can accept any dynamically provided child component but they won't modify or copy any behavior from their input components.
1307+
We consider HOCs **pure components** because they don’t mutate or copy behavior from the original component—they simply **wrap it**, enhance it, and pass through the necessary props. The wrapped component remains decoupled and reusable.
12551308
12561309
```javascript
12571310
const EnhancedComponent = higherOrderComponent(WrappedComponent);
12581311
```
1312+
Let's take an example of a `withAuth` higher-order component (HOC) in React. This HOC will check if a user is authenticated and either render the wrapped component if authenticated or redirect (or show a message) if not.
1313+
1314+
**withAuth HOC Example:**
1315+
```jsx
1316+
import React from 'react';
1317+
import { Navigate } from 'react-router-dom'; // For redirection (assuming React Router v6)
1318+
1319+
const isAuthenticated = () => {
1320+
// e.g., check for a valid token in localStorage or context
1321+
return !!localStorage.getItem('authToken');
1322+
};
1323+
1324+
function withAuth(WrappedComponent) {
1325+
return function AuthenticatedComponent(props) {
1326+
if (!isAuthenticated()) {
1327+
// User is NOT authenticated, redirect to login page
1328+
return <Navigate to="/login" replace />;
1329+
}
1330+
1331+
// User is authenticated, render the wrapped component
1332+
return <WrappedComponent {...props} />;
1333+
};
1334+
}
1335+
1336+
export default withAuth;
1337+
```
1338+
**Usage**
1339+
```jsx
1340+
import React from 'react';
1341+
import withAuth from './withAuth';
1342+
1343+
function Dashboard() {
1344+
return <h1>Welcome to the Dashboard!</h1>;
1345+
}
1346+
1347+
// Wrap Dashboard with withAuth HOC
1348+
export default withAuth(Dashboard);
1349+
```
12591350
12601351
HOC can be used for many use cases:
12611352
1262-
1. Code reuse, logic and bootstrap abstraction.
1263-
2. Render hijacking.
1264-
3. State abstraction and manipulation.
1265-
4. Props manipulation.
1353+
1. Code reuse, logic and bootstrap abstraction (e.g., fetching data, permissions, theming).
1354+
2. Render hijacking (e.g., conditional rendering or layout changes).
1355+
3. State abstraction and manipulation(e.g., handling form logic).
1356+
4. Props manipulation(e.g., injecting additional props or filtering them).
1357+
1358+
Some of the real-world examples of HOCs in react eco-system:
1359+
1. connect() from react-redux
1360+
2. withRouter() from React Router v5
1361+
3. withTranslation() from react-i18next
1362+
4. withApollo() from Apollo client
1363+
5. withFormik from Formik library
1364+
6. withTheme from styled components
12661365
12671366
**[⬆ Back to Top](#table-of-contents)**
12681367
@@ -7415,7 +7514,52 @@ Technically it is possible to write nested function components but it is not sug
74157514
74167515
**[⬆ Back to Top](#table-of-contents)**
74177516
7418-
7517+
307. ### How does React Fiber works? Explain in detail.
7518+
7519+
React Fiber is the **core engine** that enables advanced features like **concurrent rendering**, **prioritization**, and **interruptibility** in React. Here's how it works:
7520+
7521+
### 1. **Fiber Tree Structure**
7522+
7523+
Each component in your app is represented by a **Fiber node** in a tree structure. A Fiber node contains:
7524+
* Component type
7525+
* Props & state
7526+
* Pointers to parent, child, and sibling nodes
7527+
* Effect tags to track changes (e.g., update, placement)
7528+
* This forms the **Fiber Tree**, a data structure React uses instead of the traditional call stack.
7529+
7530+
### 2. **Two Phases of Rendering**
7531+
7532+
#### **A. Render Phase (work-in-progress)**
7533+
7534+
* React builds a **work-in-progress Fiber tree**.
7535+
* It walks through each component (begin phase), calculates what needs to change, and collects side effects (complete phase).
7536+
* This phase is **interruptible**—React can pause it and resume later.
7537+
#### **B. Commit Phase**
7538+
7539+
* React applies changes to the **Real DOM**.
7540+
* Runs lifecycle methods (e.g., `componentDidMount`, `useEffect`).
7541+
* This phase is **non-interruptible** but fast.
7542+
7543+
### 3. **Work Units and Scheduling**
7544+
7545+
* React breaks rendering into **units of work** (small tasks).
7546+
* These units are scheduled based on **priority** using the **React Scheduler**.
7547+
* If time runs out (e.g., user starts typing), React can **pause and yield** control back to the browser.
7548+
7549+
### 4. **Double Buffering with Two Trees**
7550+
7551+
* React maintains two trees:
7552+
* **Current Tree** – what's visible on the screen.
7553+
* **Work-In-Progress Tree** – the next version being built in memory.
7554+
* Only after the new tree is fully ready, React **commits** it, making it the new current tree.
7555+
7556+
### 5. **Concurrency and Prioritization**
7557+
7558+
* React can prepare multiple versions of UI at once (e.g., during slow data loading).
7559+
* Updates can be **assigned priorities**, so urgent updates (like clicks) are handled faster than background work.
7560+
7561+
**[⬆ Back to Top](#table-of-contents)**
7562+
74197563
## Old Q&A
74207564
74217565
1. ### Why should we not update the state directly?

0 commit comments

Comments
 (0)