Skip to content

Commit 6a24445

Browse files
committed
updated
1 parent 424a21a commit 6a24445

File tree

4 files changed

+487
-0
lines changed

4 files changed

+487
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
# 100 React Questions (Controlled & Uncontrolled Components)
2+
3+
## Q1. What are Controlled Components in React? `V. IMP.`
4+
5+
A controlled component is a component whose form elements (like input fields or checkboxes) are `controlled by the state` of the application.
6+
7+
```javascript
8+
const Controlled = () => {
9+
// State to store the input value
10+
const [inputValue, setInputValue] = useState("");
11+
12+
// Event handler for input changes
13+
const handleInputChange = (e) => {
14+
// Update the state with the new input value
15+
setInputValue(e.target.value);
16+
};
17+
18+
return (
19+
<div>
20+
{/* Input controlled by the state */}
21+
<input type="text" value={inputValue} onChange={handleInputChange} placeholder="Type..." />
22+
23+
{/* Display the current state value */}
24+
<p>You typed: {inputValue}</p>
25+
</div>
26+
);
27+
};
28+
29+
export default Controlled
30+
```
31+
32+
## Q2. What are the Differences between Controlled & Uncontrolled Components? `V. IMP.`
33+
34+
| Feature | Controlled Components | Uncontrolled Components |
35+
|---|---|---|
36+
| Value management | Controlled by `React state` | Not controlled by React state |
37+
| State updates | Event handlers `update React state` | No explicit state update; values accessed directly from DOM |
38+
| Refs | Don't depend on useRef() | Commonly uses `useRef()` to access element values |
39+
| Re-rendering | `Re-renders` on state changes | Less re-rendering due to decoupled values |
40+
| Recommendation | A `Recommended` and standard practice for form handling 🏆 | Useful in certain scenarios but less common best practice |
41+
42+
43+
### Controlled Component
44+
```javascript
45+
const Controlled = () => {
46+
// State to store the input value
47+
const [inputValue, setInputValue] = useState("");
48+
49+
// Event handler for input changes
50+
const handleInputChange = (e) => {
51+
// Update the state with the new input value
52+
setInputValue(e.target.value);
53+
};
54+
55+
return (
56+
<div>
57+
{/* Input controlled by the state */}
58+
<input type="text" value={inputValue} onChange={handleInputChange} placeholder="Type..." />
59+
60+
{/* Display the current state value */}
61+
<p>You typed: {inputValue}</p>
62+
</div>
63+
);
64+
};
65+
66+
export default Controlled
67+
```
68+
69+
### Uncontrolled Component
70+
```javascript
71+
const Uncontrolled = () => {
72+
// Create a ref to access the input value
73+
const inputRef = useRef(null);
74+
75+
const handleClick = () => {
76+
// Access the input value directly using ref
77+
const value = inputRef.current.value;
78+
alert(`You typed: ${value}`);
79+
};
80+
81+
return (
82+
<div>
83+
{/* Uncontrolled input with ref */}
84+
<input type="text" ref={inputRef} placeholder="Type something..." />
85+
86+
<button onClick={handleClick}>Click</button>
87+
</div>
88+
);
89+
};
90+
91+
export default Uncontrolled
92+
```
93+
94+
## Q3. What are characteristics of controlled components?
95+
96+
* **State Control**: The value of the form element is stored in the component's state.
97+
98+
* **Event Handling**: Changes to the form element trigger an event (e.g., onChange for input fields).
99+
100+
* **State Update**: The event handler updates the component's state with the new value of the form element.
101+
102+
* **Re-rendering**: The component re-renders with the updated state, and the form element reflects the new value.
103+
104+
```javascript
105+
const Controlled = () => {
106+
// State to store the input value
107+
const [inputValue, setInputValue] = useState("");
108+
109+
// Event handler for input changes
110+
const handleInputChange = (e) => {
111+
// State update
112+
setInputValue(e.target.value);
113+
};
114+
115+
return (
116+
<div>
117+
{/* Event Handling */}
118+
<input type="text" value={inputValue} onChange={handleInputChange} placeholder="Type..." />
119+
120+
{/* Display the current state value */}
121+
<p>You typed: {inputValue}</p>
122+
</div>
123+
);
124+
};
125+
126+
export default Controlled
127+
```
128+
129+
## Q4. What are the advantages of using controlled components in React forms?
130+
131+
* Single Source of Truth: Form element values are managed by React state, ensuring data consistency.
132+
133+
* Predictable Updates: Facilitates form validation, dynamic rendering, and seamless integration with React's lifecycle methods.
134+
135+
* Better Control and Maintainability: Offers superior control and manageability compared to uncontrolled components, making them the preferred approach for React form handling.
136+
137+
## Q5. How to handle forms in React?
138+
139+
The preferred and recommended approach for handling forms in React is `by using controlled components`.
140+
141+
## Q6. How can you handle multiple input fields in a controlled form?
142+
143+
Maintain `seperate state variables` for each input and update them individually using the `onChange event`.
144+
145+
## Q7. How do you handle form validation in a controlled component?
146+
147+
By using conditional rendering based on the state and validate input values before updating the state.
148+
149+
## Q8. In what scenarios might using uncontrolled components be advantageous?
150+
151+
Uncontrolled components can be beneficial when integrating with non-React libraries, or when dealing with forms where controlled components are not possible.
152+
153+
<!---
154+
Adarsh
155+
3rd August 2024
156+
05:22 AM
157+
(19:50)
158+
--->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
# 100 React Questions (Code Splitting)
2+
3+
## Q1. What is Code Splitting in React? `V. IMP.`
4+
5+
Code splitting is a technique to split the JavaScript bundle into `smaller chunks`, which are `loaded on-demand`.
6+
7+
## Q2. How to Implement Code Splitting in React? `V. IMP.`
8+
9+
* Use React.lazy() to lazily import components.
10+
11+
* Wrap components with Suspense to handle loading.
12+
13+
* Configure your build tool (e.g., Webpack) for dynamic imports.
14+
15+
```javascript
16+
const CodeSplit = () => {
17+
return <div>My component!</div>;
18+
};
19+
20+
export default CodeSplit;
21+
```
22+
23+
### App.js
24+
```javascript
25+
import React, { lazy, Suspense } from "react";
26+
27+
const CodeSplit = lazy(() => import("./Others/CodeSplit"));
28+
29+
function App() {
30+
return (
31+
<div>
32+
<Suspense fallback={<div>Loading...</div>}>
33+
<CodeSplit />
34+
</Suspense>
35+
</div>
36+
);
37+
}
38+
```
39+
40+
## webpack installation command
41+
```javascript
42+
// npm install webpack webpack-cli --save-dev
43+
const path = require('path');
44+
45+
module.exports = {
46+
// other webpack configuration...
47+
output: {
48+
filename: '[name].bundle.js',
49+
path: path.resolve(__dirname, 'dist'),
50+
},
51+
};
52+
```
53+
54+
## Q3. What is the role of Lazy and Suspense methods in React? `V. IMP.`
55+
56+
* React.lazy is a function that allows you to `load a component lazily`.
57+
58+
* It enables code splitting by allowing you to import a component asynchronously/dynamically, meaning the component is loaded only when needed.
59+
60+
* The Suspense component is used to display a fallback UI while the lazily loaded component is being fetched.
61+
62+
### App.js
63+
```javascript
64+
import React, { lazy, Suspense } from "react";
65+
66+
const CodeSplit = lazy(() => import("./Others/CodeSplit"));
67+
68+
function App() {
69+
return (
70+
<div>
71+
<Suspense fallback={<div>Loading...</div>}>
72+
<CodeSplit />
73+
</Suspense>
74+
</div>
75+
);
76+
}
77+
```
78+
79+
## Q4. What are the Pros and Cons of Code Splitting?
80+
81+
### Pros:
82+
| Pros of Code Splitting | Description |
83+
|---|---|
84+
| Faster Initial Load Time | Code splitting reduces the initial load time of your application by only loading the necessary code for the current view or feature. Good for performance. |
85+
| Optimized Bandwidth Usage | By loading only the code needed for a specific page, it reduces the amount of data transferred over the network. Good for slow networks. |
86+
| Improved Caching | Smaller, more focused code chunks are more likely to be cached by the browser. |
87+
| Parallel Loading | Multiple smaller chunks can be loaded simultaneously, leading to faster overall loading times. |
88+
| Easier Maintenance | Code splitting can make your codebase more modular, independent, and easier to maintain. |
89+
90+
### Cons:
91+
| Cons of Code Splitting | Description |
92+
|---|---|
93+
| Complexity | Implementing code splitting introduces additional complexity to your application. This complexity can make the development process slow. |
94+
| Tooling Dependencies | Proper code splitting often requires specific build tools and configurations, such as Webpack and Babel. Managing these tools is challenging. |
95+
| Potential for Runtime Errors | Dynamically loading code at runtime can introduce the possibility of runtime errors. Careful testing is necessary to catch such issues. |
96+
| Increased Number of Requests | Code splitting may increase the number of HTTP requests needed to fetch all the necessary chunks. This can impact performance. |
97+
| Learning Curve | Developers who are new to code splitting may need time to understand the concepts and best practices. This can be a challenging. |
98+
99+
## Q5. What is the role of the import() function in code splitting?
100+
101+
The import() function returns a promise that allow `dyanmic loading of modules`.
102+
103+
### App.js
104+
```javascript
105+
import React, { lazy, Suspense } from "react";
106+
107+
const CodeSplit = lazy(() => import("./Others/CodeSplit"));
108+
109+
function App() {
110+
return (
111+
<div>
112+
<Suspense fallback={<div>Loading...</div>}>
113+
<CodeSplit />
114+
</Suspense>
115+
</div>
116+
);
117+
}
118+
```
119+
120+
## Q6. What is the purpose of the fallback prop in Suspense?
121+
122+
The fallback prop provides a `loading indicator` or UI while the dynamically imported component is being loaded.
123+
124+
## Q7. Can you dynamically load CSS files using code splitting in React?
125+
126+
`Yes`, using dynamic import() for CSS files allows you to load styles on-demand along with the corresponding components.
127+
128+
## Q8. How do you inspect and analyze the generated chunks in a React application?
129+
130+
Use tools like `Webpack Bundle Analyzer` to analyze the size and composition of chunks.
131+
132+
<!---
133+
Adarsh
134+
3rd August 2024
135+
05:43 AM
136+
(14:40)
137+
--->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# 100 React Questions (Hooks - useContext/useReducer)
2+
3+
## Q1. What is the role of useContext() hook? `V. IMP.`
4+
5+
useContext in React provides a way to pass data from parent to child component without using props.
6+
7+
### MyContext.js
8+
```javascript
9+
import { createContext } from "react";
10+
11+
const MyContext = createContext();
12+
export default MyContext;
13+
```
14+
15+
### Parent.js
16+
```javascript
17+
const Parent = () => {
18+
const contextValue = "Hello from Context!";
19+
20+
return (
21+
<MyContext.Provider value={contextValue}>
22+
{/* Your component tree */}
23+
<Child />
24+
</MyContext.Provider>
25+
);
26+
};
27+
export default Parent;
28+
```
29+
30+
### Child.js
31+
```javascript
32+
const Child = () => {
33+
const contextValue = useContext(MyContext);
34+
35+
return <p>{contextValue}</p>;
36+
37+
// return (
38+
// <MyContext.Consumer>
39+
// {(contextValue) => <div>{contextValue}</div>}
40+
// </MyContext.Consumer>
41+
// );
42+
};
43+
export default Child;
44+
```
45+
46+
## Q2. What is createContext() method? What are Provider & Consumer properties?
47+
48+
* The createContext() function returns an object with Provider and Consumer properties.
49+
50+
* The Provider property is responsible for providing the context value to all its child components.
51+
52+
* The useContext() method or Consumer property can be used to consume the context value in child components.
53+
54+
## Q3. When to use useContext() hook instead of props in real applications?
55+
56+
Use useContext instead of props when you want to `avoid prop drilling` and access context values directly within deeply nested components.
57+
58+
| Feature | Description |
59+
|---|---|
60+
| Theme Switching (Dark/Light) | Centralize and pass theme selection from parent to all child components. |
61+
| Localization (Language Selection) | Centralize and pass language selection from parent to all child components. |
62+
| Centralize Configuration Settings | Centralize common settings like API endpoints. Changes in parent affect all children. |
63+
| User Preferences | Centralize user preferences beyond theme and localization. |
64+
| Notification System | Access notification state from context for components triggering or displaying notifications. |
65+
66+
## Q4. What are the similarities between useState() and useReducer() hook?
67+
68+
## Q5. What is useReducer() hook? When to use useState() and when useReducer()? `V. IMP.`
69+
70+
## Q6. What are the differences between useState() and useReducer() Hook?
71+
72+
## Q7. What are dispatch & reducer function in useReducer Hook?
73+
74+
## Q8. What is the purpose of passing initial state as an object in UseReducer?
75+
76+
<!---
77+
Adarsh
78+
2nd August 2024
79+
09:13 PM
80+
(19:25)
81+
--->

0 commit comments

Comments
 (0)