17 |
18 |
19 |
20 |
21 |
22 |
563 |
564 |
565 |
566 |
567 |
568 |
--------------------------------------------------------------------------------
/Important Questions/DEV_QUESTIONS.md:
--------------------------------------------------------------------------------
1 | # Dev Questions
2 |
3 | ## Difference between ReactJs and NextJs
4 | - `ReactJs` is a JavaScript library for building user interfaces and `NextJs` is a framework built on top of ReactJs.
5 | - To do `ReactJS`, you need to know Javacript, but to do `NextJS`, you need to know ReactJS as well as Javascript.
6 | - `ReactJs` is a client side rendering library and `NextJs` is a server side rendering framework.
7 | - In ReactJs, first the code comes inside the browser and then it renders, but in NextJs, the code first renders inside the server and then it comes to the browser. So it is good for SEO purposes. Now, the google crawler, will see the pages at first in the server side only before coming to the browser.
8 | - Also `React` Official documentation says that, if you are building a website which is not going to be small or project based, then you can use ReactJs, but if you are building a large project, then you should use ReactJs's framework i.e, `NextJs`.
9 |
10 | - ReactJs is a library for building UI components and NextJs is a framework for building full stack ReactJs applications.
11 | - ReactJs is a library for building UI components and NextJs is a library for building UI components and routing between them.
12 | - ReactJs is a library for building UI components and NextJs is a library for building UI components and routing between them.
13 |
14 |
15 | ## Which is better in ReactJs, Class Component or Functional Component?
16 | > Both class components and functional components are used in React, but functional components have become the preferred approach in recent years.
17 |
18 | - `Simplicity and readability`: Functional components tend to be simpler and more concise than class components. They use regular JavaScript functions and don't require managing a separate state object. This simplicity often leads to improved code readability and maintainability.
19 |
20 | - `State`: Class components are called stateful components because it allows you to store and update component state. Functional components (stateless components) don't have access to state by default, but React introduced the useState hook to address this need. With useState, functional components can achieve similar functionality to class component state.
21 |
22 | - `Lifecycle methods`: Class components have access to lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount. Although functional components didn't have direct equivalents to these methods initially, React introduced the useEffect hook to address this need. With useEffect, functional components can achieve similar functionality to class component lifecycle methods.
23 |
24 | - `Reusability and composition`: Functional components promote reusability and composability through the use of hooks. Hooks allow you to extract and reuse specific pieces of stateful or side-effect logic, making it easier to build and maintain complex UI components.
25 |
26 | - `Performance`: Functional components are generally more performant than class components. This is because functional components leverage React's built-in optimization mechanisms like memoization and hooks, which can help reduce unnecessary re-renders and improve overall performance.
27 |
28 |
29 |
30 | ## Difference between setInterval() and setTimeout
31 | > `setTimeout()` executes a function once after a specified delay, while `setInterval()` repeatedly executes a function at a fixed interval until it is canceled. `clearTimeout()` is used to cancel the setTimeout and `clearInterval()` is used to cancel the setInterval
32 |
33 | ```
34 | // SetTimeout (Executes the function after 2 seconds)
35 |
36 | const timeoutId = setTimeout(() => {
37 | console.log("This will be executed once after 2 seconds.");
38 | }, 2000);
39 |
40 | clearTimeout(timeoutId); // Cancel the timeout before it executes
41 |
42 | ```
43 |
44 | ```
45 | // SetInterval (Executes the function every 1 second)
46 |
47 | const intervalId = setInterval(() => {
48 | console.log("This will be executed every 1 second.");
49 | }, 1000);
50 |
51 | setTimeout(() => {
52 | clearInterval(intervalId); // Cancel the interval after 5 seconds
53 | }, 5000);
54 | ```
55 |
56 |
57 | ## Differentiate between Promise and async/await
58 | > Both `Promises` and `async/await` are mechanisms in JavaScript that deal with asynchronous code execution and make it easier to work with asynchronous operations. However, they have different syntax and underlying mechanisms.
59 |
60 | - Promises are objects that represent the eventual completion or failure of an asynchronous operation and allow you to handle the result.
61 | - They have three states: pending, fulfilled, or rejected.
62 | - Promises provide a .then() method to handle the successful completion of an operation and a .catch() method to handle any errors.
63 | - You can chain multiple .then() methods to handle multiple asynchronous operations sequentially.
64 |
65 | ```
66 | const fetchData = () => {
67 | return new Promise((resolve, reject) => {
68 | setTimeout(() => {
69 | resolve('Data fetched successfully');
70 | }, 2000);
71 | });
72 | };
73 |
74 | fetchData()
75 | .then((data) => {
76 | console.log(data);
77 | })
78 | .catch((error) => {
79 | console.log(error);
80 | });
81 |
82 | ```
83 |
84 | - `async/await` is a syntactical feature introduced in ECMAScript 2017 (ES8) that allows you to write asynchronous code in a more synchronous-like manner.
85 | - It provides a cleaner and more readable way to handle Promises.
86 | - The async keyword is used to define an asynchronous function, and within that function, you can use the await keyword to pause the execution until a Promise is fulfilled and retrieve its result.
87 | - await can only be used within an async function.
88 | - async/await code is structured like synchronous code, making it easier to understand and write.
89 |
90 | ```
91 | const fetchData = () => {
92 | return new Promise((resolve, reject) => {
93 | setTimeout(() => {
94 | resolve('Data fetched successfully');
95 | }, 2000);
96 | });
97 | };
98 |
99 | const fetchDataAsync = async () => {
100 | try {
101 | const data = await fetchData();
102 | console.log(data);
103 | } catch (error) {
104 | console.log(error);
105 | }
106 | };
107 |
108 | fetchDataAsync();
109 |
110 | ```
111 |
112 | - In summary, Promises are a lower-level abstraction that allow you to handle asynchronous operations using .then() and .catch(), while async/await is a higher-level syntactic sugar built on top of Promises, providing a more synchronous-like coding experience.
113 |
114 |
115 | ## Explain what is Redux? / What is state management in React?
116 | Let's take an e-commerce website for example. An e-commerce website will have several components like the cart component, user profile component, previously viewed section component, and so on.
117 |
118 | We'll take the cart component which displays the number of items in a user's cart. The state of the cart component will consist of all the items the user has added to the cart and the total number of those items. At all times the application is up and running, this component has to show the updated number of items in the user's cart.
119 |
120 | Whenever a user adds an item to the cart, the application has to internally handle that action by adding that item to the cart object. It has to maintain its state internally and also show the user the total number of items in the cart in the UI.
121 |
122 | Similarly, removing an item from the cart should decrease the number of items in the cart internally. It should remove the item from the cart object and also display the updated total number of items in the cart in the UI.
123 |
124 | We may very well maintain the internal state of the components inside them, but as and when an application grows bigger, it may have to share some state between components. This is not just only to show them in the view, but also to manage or update them or perform some logic based on their value.
125 |
126 | This task of handling multiple states from multiple components efficiently can become challenging when the application grows in size.
127 |
128 | This is where Redux comes into the picture. Being a state management library, Redux will basically store and manage all the application's states.
129 |
130 | <<<<<<<<< Redux Lifecycle >>>>>>>>
131 |
132 |
133 | +------ Javascript -----+
134 | | (app) |
135 | | |
136 | | |
137 | Store Action
138 | | |
139 | | |
140 | | |
141 | +-------- Reducers -----+
142 |
143 |
144 | So, (App) --> Action --> Reducers --> Store --> (App)
145 |
146 | For example (Comparing Redux to a Ice-cream shop)
147 | - Action : Customers giving the order to the shopkeeper
148 | - Reducers : Shopkeeper taking the order from customer and giving it to the store
149 | - Store : Store is the place where all the items are stored\
150 |
151 |
152 |
153 | ## Differentiate between ForEach, Map, Filter
154 | > `forEach()`, `map()`, and `filter()` are array methods in JavaScript. They are used to iterate over an array and perform different actions on each item in the array.
155 |
156 | ```
157 |
158 | (a) forEach():
159 | forEach is used to iterate through each element of an array and execute a provided function for each element.
160 | It does not create a new array; it modifies the existing array in place.
161 | It's generally used when you want to perform some action for each element in the array but do not need to return a new array.
162 |
163 | Example:
164 | const numbers = [1, 2, 3, 4, 5];
165 |
166 | numbers.forEach(number => {
167 | console.log(number * 2);
168 | });
169 |
170 | (b) map():
171 | map is used to create a new array by applying a provided function to each element in the original array.
172 | It returns a new array with the same length as the original array.
173 | The values in the new array are the results of applying the function to each element.
174 |
175 | Example:
176 | const numbers = [1, 2, 3, 4, 5];
177 |
178 | const doubledNumbers = numbers.map(number => number * 2);
179 | console.log(doubledNumbers); // [2, 4, 6, 8, 10]
180 |
181 | (c) filter():
182 | filter is used to create a new array with elements that pass a provided test (specified by a function).
183 | It returns a new array containing only the elements for which the test function returns true.
184 |
185 | The length of the new array may be different from the original array.
186 | Example:
187 | const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
188 |
189 | const evenNumbers = numbers.filter(number => number % 2 === 0);
190 | console.log(evenNumbers); // [2, 4, 6, 8, 10]
191 |
192 | Summary:
193 |
194 | forEach: Use when you want to perform an action for each element in the array without creating a new array.
195 | map: Use when you want to create a new array by transforming each element based on a provided function.
196 | filter: Use when you want to create a new array containing only the elements that satisfy a condition specified by a function.
197 |
198 | ```
199 |
200 |
201 | ## Can we do server side rendering in ReactJs?
202 | ``` Yes, we can do server side rendering in ReactJs using NextJs. NextJs is a framework built on top of
203 | ReactJs that provides server side rendering capabilities. It allows you to render React components on the
204 | server and send the generated HTML to the client, improving performance and SEO.
205 | - npm init vite-plugin-ssr@latest
206 | ```
207 |
208 | ## What are the performance improvement techniques we can use in ReactJs and NextJs?
209 | ```
210 | ReactJS :
211 | - useMemo
212 | - React Lazy Loading
213 |
214 | NextJs :
215 | - Server Side Rendering
216 |
217 | ```
218 |
219 |
220 | ## Implement Filter function unside react app
221 |
222 | ```
223 | const [userData, setUserData] = useState([]);
224 | const [userValue, setUserValue] = useState("");
225 |
226 |
232 | ))}
233 |
234 | ```
235 |
236 |
237 | ## Use Async to call api instead of .then
238 |
239 | ```
240 |
241 | useEffect(() => {
242 | async function callFunction() {
243 | try {
244 | const res = await axios.get(
245 | "https://jsonplaceholder.typicode.com/posts"
246 | );
247 | setUserData(res.data);
248 | console.log(res.data);
249 | } catch (err) {
250 | console.log("Error =>", err);
251 | }
252 | }
253 | callFunction();
254 | }, []);
255 |
256 | ```
257 |
258 |
259 | ## When to use ContextAPI and Redux [Link]("https://dev.to/ruppysuppy/redux-vs-context-api-when-to-use-them-4k3p) ?
260 |
261 | ```
262 |
263 | ContextAPI :
264 | - good for static data that is not often refreshed or updated
265 | - requires less boilerplate code
266 | - good for small to medium-sized applications
267 | - debugging can be hard in highly nested component
268 |
269 | Redux :
270 | - works well with both static and dynamic data
271 | - requires extensive boilerplate code
272 | - good for large applications with complex state management
273 | - Redux Dev Tools for easy debugging
274 |
275 | ```
276 |
277 | ## What are react hooks?
278 | > ```React Hooks``` are functions that let you use state and other React features in functional components. Before hooks, state and lifecycle methods could only be used in class components.
279 |
280 | - ```useState```: Allows you to add state to functional components.
281 | - ```useEffect```: Allows you to perform side effects in your functional components.
282 | - ```useContext```: Allows you to use context in your functional components.
283 | - ```useRef```: Allows you to create mutable object that persists for the entire lifecycle of the component.
284 | - ```useReducer```: Allows you to manage state transitions in a more predictable way.
285 | - ```useCallback```: Allows you to memoize functions to prevent unnecessary re-renders.
286 | - ```useMemo```: Allows you to memoize values to prevent unnecessary calculations.
287 |
288 |
289 | ## When to use map and forEach in ReactJs?
290 | `map()` and `forEach()` are both array methods in JavaScript that can be used to iterate over an array
291 | and perform an action on each element. However, they have different use cases in ReactJS.
292 |
293 |
294 | MAP() :
295 | - returns a new array with transformed elements.
296 | - chainable since returns new array. (eg: `array.map().filter().reduce()`)
297 |
298 | FOREACH() :
299 | - does not return anything. (returns `undefined`)
300 | - not chainable since it returns undefined.
301 |
302 | MAP() :
303 | ```
304 |
305 | const numbers = [1, 2, 3, 4, 5];
306 | const doubled = numbers.map(num => num * 2);
307 | console.log(doubled); // Output: [2, 4, 6, 8, 10]
308 |
309 | ```
310 |
311 | FOREACH() :
312 | ```
313 |
314 | const numbers = [1, 2, 3, 4, 5];
315 | numbers.forEach(num => {
316 | console.log(num * 2);
317 | });
318 | // Output: 2, 4, 6, 8, 10 (each on a new line)
319 |
320 | ```
321 |
322 | MAP() :
323 | ```
324 |
325 | import React from 'react';
326 |
327 | const items = ['Apple', 'Banana', 'Cherry'];
328 |
329 | function ItemList() {
330 | return (
331 |
;
357 | }
358 |
359 | export default ItemList;
360 |
361 | ```
362 |
363 | ## When to use slice and splice?
364 | > `slice()` and `splice()` are array methods in JavaScript that can be used to extract or modify elements in an array. They have different use cases and behaviors.
365 |
366 | SLICE() :
367 | - returns a portion of an array into a new array from begin to end (end not included)
368 | - does not modify the original array
369 |
370 | SPLICE() :
371 | - returns an array of the removed elements
372 | - modifies the original array by removing, replacing, or adding elements
373 |
374 | SLICE() :
375 | ```
376 |
377 | const fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
378 | const citrus = fruits.slice(1, 3);
379 |
380 | console.log(citrus); // ["Orange", "Lemon"]
381 | console.log(fruits); // ["Banana", "Orange", "Lemon", "Apple", "Mango"]
382 |
383 | ```
384 |
385 | SPLICE() :
386 | ```
387 |
388 | const fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
389 | const removed = fruits.splice(2, 2, 'Kiwi', 'Grapes');
390 |
391 | console.log(removed); // ["Lemon", "Apple"]
392 | console.log(fruits); // ["Banana", "Orange", "Kiwi", "Grapes", "Mango"]
393 |
394 | ```
395 |
396 | ## difference between Props and State ?
397 | > `Props` and `State` are both plain JavaScript objects used in React to manage data and control the behavior of components. However, they have different use cases and behaviors.
398 |
399 | PROPS :
400 | - Props are immutable, cannot be modified by the component itself.
401 | - Props are like function parameters
402 | - passed from one component to another
403 |
404 | STATE :
405 | - State is mutable, can be modified by the component itself using `setState()`.
406 | - State is similar to variables
407 | - passed within the component
408 |
409 | ## How do browser read JSX?
410 | - Babel compiles JSX into JavaScript that browsers can understand, otherwise browsers are not capable of reading JSX directly.
411 |
412 | ## What is Reconcliation in ReactJs?
413 | - `Reconciliation` is the process by which React updates the DOM in response to changes in the component tree. When a component's state or props change, React compares the new tree with the previous tree and determines what changes need to be made to the DOM to reflect the new state of the application.
414 |
415 | - ```Keys``` play a crucial role in the reconciliation process when dealing with lists of elements. They help React identify which items have changed, been added, or been removed. Without keys, React would not be able to correctly determine these changes, leading to inefficient updates and potential bugs.
416 |
417 | ## Difference between normal function and arrow function in JS?
418 | - ```Normal Functions``` are more versatile in terms of this binding and can be used in a variety of contexts, including as constructors and methods.
419 | - ```Arrow Functions``` provide a more concise syntax and lexically bind this, making them more suitable for situations where the function does not need its own this context, such as callbacks and functional programming.
--------------------------------------------------------------------------------