Wa0004.
Wa0004.
Wa0004.
map transforms each element of an array and creates a new array which
contains the transformed elements. whereas filter will creates a new array
with only those elements which satisfies the specified condition.
map method will return a new array with the transformed values. forEach
method does not return a new array.
map method can be used with other array methods like filter method.
whereas forEach method cannot be used with other array methods as it
does not return any array.
Pure functions are the functions which will return same output for same
arguments passed to the function.
function greeting(name) {
return `Hello ${name}`;
}
console.log(greeting("Saikrishna Nangunuri"));
Impure Functions:
Impure functions are the functions which will return inconsistent output for
same arguments passed to the function.
Ref: https://www.scaler.com/topics/pure-function-in-javascript/
for-in:
for-of:
https://stackoverflow.com/questions/29285897/difference-between-for-in-
and-for-of-statements?answertab=scoredesc#tab-top
Apply method will invokes the function immediately with given this value
and allow us to pass the arguments as an array.
Bind method will return a new function with the given this value and
arguments which can be invoked later.
2. Arrow functions
3. Template literals
4. Destructuring assignment
6. Default parameters
7. Promises
8. Modules
10. Classes
Uses:
1. Concatenating arrays.
let x = [1,2];
let y = [3,4];
function createExample(arg1,arg2){
console.log(arg1,arg2);
}
createExample(…a)
This is useful when we dont know how many parameters a function may
receive and you want to capture all of them as an array.
function Example(...args){
console.log(args)
}
Example(1,2,3,4);
Avoid duplicates. This make software more maintainable and less error-
prone.
SOLID:
Object literal :
Object constructor :
Object.Create() :
This is used when we want to inherit properties from an existing object
while creating a new object.
let animal = {
name: "Animal name"
}
Object.assign() :
This is used when we want to include properties from multiple other objects
into new object we are creating.
let lesson = {
lessonName: "Data structures"
};
let teacher= {
teacher: "Saikrishna"
};
let data = {
name: "Sai",
lang: "English"
};
Object.keys(data) // ["name","lang"]
Object.values(data) // ["Sai","english"]
Object.entries(data) // [["name","Sai"],["lang","English"]]
Will make the object immutable ( prevents the addition of new propeties
and prevents modification of existing properties)
let data = {
a : 10
};
Object.freeze(data);
data.a= 20;
data.c = 30;
console.log(data)
Object.Seal():
Will prevent the addition of new properties but we can modify existing
properties.
let data = {
a : 10
};
Object.seal(data);
data.a = 20;
data.c = 30;
console.log(data)
Output:
data: {
a: 20
}
Array.prototype.forEach = function(callback) {
for (var i = 0; i < this.length; i++) {
if (i in array) {
callback.call(array[i], i, array);
array.forEach((element,id,arrd)=>{
console.log(`${element},${id}`,arrd)
})
They are defined by using function* and it contains one or more yield
expressions.
The main method of generator is next(). when called, it runs the execution
until the nearest yield.
https://javascript.info/generators
function* generatorFunction() {
yield 1;
yield 2;
yield 3;
return 4
}
https://www.tutorialsteacher.com/javascript/prototype-in-javascript
function Student(){
this.name = "Saikrishna",
this.exp= "8"
}
Student.prototype.company = "Hexagon"
console.log(std1);
console.log(std2)
functions which are executed immediately once they are mounted to the
stack is called iife.
https://www.geeksforgeeks.org/immediately-invoked-function-
expressions-iife-in-javascript/
https://www.tutorialsteacher.com/javascript/immediately-invoked-function-
expression-iife
(function(){
console.log("2222")
})()
cors works by adding specific http headers to control which origins have
access to the resources and under what conditions.
String
number
boolean
undefined
Bigint
symbol
Non-Primitive datatypes:
Object
Array
Date
Typescript is the superset of javascript and has all the object oriented
features.
Authorization:
Undefined:
means the variable has been declared but not assigned any value yet.
console.log(newArr) // [2,3]
Splice:
console.log(arr); // [1,28,9,6,10]
console.log(newArr); // [3,4,5,0]
const user = {
"age": 10,
"name": "Saikrishna"
}
setInterval(function(){
console.log("Prints Hello after every 2 seconds");
},2000);
promise.then((response)=>{
console.log("success",response)
}).catch((err)=>{
console.log("failed",err)
})
Each and every function in javascript has access to its outer lexical
environment means access to the variables and functions present in the
environments of its parents
function Outer(){
var a = 10;
function Inner(){
console.log(a);
}
return Inner;
}
Usecases:
setTimeOut
function Print(){
console.log("Print method");
}
function Hello(Print){
Hello(Print);
Output:
Hello method
Print method
Advantages:
callback functions
Abstraction
Code reusability
Encapsulation
It means all type checks are done at run time ( When program is executing
).
So, we can just assign anything to the variable and it works fine.
let a;
a = 0;
console.log(a) // 0
a = "Hello"
console.log(a) // "Hello"
SessionStorage:
axios.interceptors.request.use((config)=>{
if(longUrls.include(url)){
config.timeout = 1000;
}
return config;
}
axios.interceptors.response.use((response)=>{
return response;
})
In javascript, variables and functions can be used before declaring it. The
javascript compiler moves all the declarations of variables and functions on
top. so there will not be any error. This is called hoisting.
Variables declared with var are function scoped.( available through out
the function where its declared ) or global scoped( if defined outside
the function ).
Reassignment:
Hoisting:
let and const - gets hoisted to the top of the scope but does not get
assigned any value.(temporary dead zone)
const a = 1<2<3;
const b = 1>2>3;
console.log(a,b) //true,false
Will wait for all of the promises to resolve or any one of the promise
reject.
Promise.allSettled:
Will wait for all the promises to settle (either fulfilled or rejected).
Promise.any:
Will return if any one of the promise fulfills or rejects when all the
promises are rejected.
Promise.race:
https://medium.com/@log2jeet24/javascript-different-types-of-promise-
object-methods-to-handle-the-asynchronous-call-fc93d1506574
3. Arrow function does not have their own this. Instead, they inherit this from
the surrounding code at the time the function is defined.
4. Arrow functions cannot be used as constructors. Using them with the 𝙣𝙚𝙬
keyword to create instances throws a TypeError.
It will return the first element of array that passes specified condition.
function findMethod(){
let arr = [{id:1,name:"sai"},{id:2,name:"krishna"}];
let data = arr.find(x=> x.id==2)
console.log(data)
}
findMethod()
findIndex:
It will return the index of first element of an array that passes the
specified condition.
function findMethod(){
let arr = [{id:1,name:"sai"},{id:2,name:"krishna"}];
let data = arr.findIndex(x=> x.id==2)
console.log(data)
}
findMethod()
Output:
2
Advantages:
Output:
Start, End,Promise,Timeout.
const a = 1<2<3;
const b = 1>2>3;
console.log(a,b) //true,false
true, false
Similarly, 1 > 2 > 3 is evaluated as (1 > 2) > 3 , which becomes false >
const p = { k: 1, l: 2 };
const q = { k: 1, l: 2 };
let isEqual = p==q;
let isStartEqual = p=== q;
console.log(isEqual, isStartEqual)
OutPut:
False,False
In your code:
memory, even though they have the same properties and values.
a) 2+2 = ?
b) "2"+"2" = ?
c) 2+2-2 = ?
d) "2"+"2"-"2" = ?
Output:
// a) 2+2 = ?
console.log(2 + 2); // Output: 4
// b) "2"+"2" = ?
console.log("2" + "2"); // Output: "22" (string concatenation
// c) 2+2-2 = ?
console.log(2 + 2 - 2); // Output: 2
// d) "2"+"2"-"2" = ?
console.log("2" + "2" - "2"); // Output: 20 (string "22" is co
let a = 'jscafe'
a[0] = 'c'
Output:
“jscafe”
var x=10;
function foo(){
var x = 5;
console.log(x)
}
foo();
console.log(x)
Output: 5 and 10
In JavaScript, this code demonstrates variable scoping. When you declare a
variable inside a function using the var keyword, it creates a new variable
scoped to that function, which may shadow a variable with the same name in
an outer scope. Here's what happens step by step:
1. var x = 10; : Declares a global variable x and initializes it with the value 10 .
function x(){
for(var i=1;i<=5;i++){
setTimeout(()=>{
console.log(i)
},i*1000)
}
x();
function x(){
function closur(x){
setTimeout(()=>{
console.log(x)
},x*1000)
};
for(var i=1;i<=5;i++){
closur(i)
}
x();
function x(){
let a = 10;
function d(){
console.log(a);
}
a = 500;
return d;
}
var z = x();
z();
3. function d() { ... } : Defines a nested function named d inside the function
x .
When you run this code, it will log the value of a at the time of executing d ,
which is 500 , because d retains access to the variable a even after x has
finished executing. This behavior is possible due to closure, which allows inner
functions to access variables from their outer scope even after the outer
function has completed execution.
getData1()
getData();
function getData1(){
console.log("getData11")
}
Output:
Explanation:
In JavaScript, function declarations are hoisted to the top of their scope, while
variable declarations using var are also hoisted but initialized with undefined .
Here's what happens in your code:
getData is declared using var , so it's also hoisted to the top but
initialized with undefined .
It will throw an error because getData is undefined , and you cannot call
undefined as a function.
Therefore, if you try to run the code as is, you'll encounter an error when
attempting to call getData() .
If you want to avoid this error, you should either define getData before calling it
or use a function declaration instead of a variable declaration for getData .
Here's how you can do it:
Modification needed for code:
function func() {
try {
console.log(1)
return
} catch (e) {
console.log(2)
func()
Output: 1 & 3
Since return is encountered within the try block, the control exits the function
immediately after console.log(1) . The catch block is skipped because there are
no errors, and the code in the finally block is executed regardless of whether
an error occurred or not.
So, when you run this code, it will only print 1 and 3 to the console.
Explanation:
let a = true;
setTimeout(() => {
a = false;
}, 2000)
while(a) {
console.log(' -- inside whilee -- ');
}
Solution: https://medium.com/@iamyashkhandelwal/5-output-based-
interview-questions-in-javascript-b64a707f34d2
This code snippet creates an infinite loop. Let's break it down:
The issue here is that the while loop runs indefinitely because there's no
opportunity for the JavaScript event loop to process the setTimeout callback
and update the value of a . So, even though a will eventually become false
console.log(2);
console.log(5);
This code demonstrates the event loop in JavaScript. Here's the breakdown of
what happens:
3. : This
new Promise(res => { console.log(3); res(); }).then(() => console.log(4));
creates a new Promise. The executor function inside the Promise logs 3 to
the console and then resolves the Promise immediately with res() . The
then() method is chained to the Promise, so once it's resolved, it logs 4 to
the console.
When you run this code, the order of the output might seem a bit
counterintuitive:
Here's why:
Once the current synchronous execution is done, the event loop picks up
the resolved Promise and executes its then() callback, logging 4 .
https://medium.com/@iamyashkhandelwal/5-output-based-interview-
questions-in-javascript-b64a707f34d2
console.log("D");
Output:
D, A, E, B, C
Explanation:
return uniqueArr;
};
function removeDuplicates(arr) {
// Use the Set object to remove duplicates. This works beca
return Array.from(new Set(arr));
}
removeDuplicates([1, 2, 1, 3, 4, 2, 2, 1, 5, 6]);
console.log(checkPallindrome("madam"));
console.log(longestWord);
};
console.log(maxCount);
};
findConsecutive([1, 1, 9, 1, 9, 9, 19, 7, 1, 1, 1, 3, 2, 5, 1
// output: 3
console.log(findFactorial(4));
66. Given 2 arrays that are sorted [0,3,4,31] and [4,6,30]. Merge
them and sort [0,3,4,4,6,30,31] ?
let i = 1;
let j=1;
let array1 = arr1[0];
let array2 = arr2[0];
while(array1 || array2){
}
console.log(mergedArray)
sortedData([1,3,4,5],[2,6,8,9])
67. Create a function which will accepts two arrays arr1 and
arr2. The function should return true if every value in arr1 has
its corresponding value squared in array2. The frequency of
values must be same. (Effecient)
function isSameFrequency(arr1,arr2){
let arrFreq1={};
let arrFreq2={};
console.log(isSameFrequency([1,2,5],[25,4,1]))
function isStringCreated(str1,str2){
if(str1.length !== str2.length) return false
let freq = {};
console.log(isStringCreated('anagram','nagaram'))
function getUniqueArr(array){
const uniqueArr = [];
const seen = {};
for(let i=0; i<=array.length-1;i++){
const currentItem = array[i].name;
if(!seen[currentItem]){
uniqueArr.push(array[i]);
seen[currentItem] = true;
}
}
return uniqueArr;
}
function findMax(arr) {
if (arr.length === 0) {
return undefined; // Handle empty array case
}
return max;
}
// Example usage:
const numbers = [1, 6, -33, 9, 4, 8, 2];
console.log("Maximum number is:", findMax(numbers));
function findEvenNumbers(arr) {
const result = [];
return result;
// Example usage:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8,-8,19, 9, 10];
console.log("Even numbers:", findEvenNumbers(numbers));
function isPrime(number) {
if (number <= 1) {
return false; // 1 and numbers less than 1 are not pri
}
// Example usage:
console.log(isPrime(17)); // true
console.log(isPrime(19)); // false
return max;
}
// Example usage:
const nestedArray = [[3, 4, 58], [709, 8, 9, [10, 11]], [111,
console.log("Largest element:", findLargestElement(nestedArray
function fibonacciSequence(numTerms) {
if (numTerms <= 0) {
return [];
return sequence;
}
// Example usage:
const numTerms = 10;
const fibonacciSeries = fibonacciSequence(numTerms);
console.log(fibonacciSeries); // Output: [0, 1, 1, 2, 3, 5, 8
function countCharacters(str) {
const charCount = {}; // Object to store character counts
const len = str.length;
return charCount;
}
function quickSort(arr) {
// Check if the array is empty or has only one element
if (arr.length <= 1) {
return arr;
}
// Example usage:
const unsortedArray = [5, 2, 9, 1, 3, 6];
const sortedArray = quickSort(unsortedArray);
console.log(sortedArray); // Output: [1, 2, 3, 5, 6, 9]
function quickSort(arr) {
if (arr.length <= 1) {
return arr;
}
// Example usage
reverseWords("ChatGPT is awesome"); //"awesome is ChatGPT"
function reverseWords(sentence) {
// Split the sentence into words
let words = [];
let wordStart = 0;
for (let i = 0; i < sentence.length; i++) {
// Example usage
const sentence = "ChatGPT is awesome";
console.log(reverseWords(sentence)); // Output: "awesome is C
function flattenArray(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
result.push(next);
}
}
return result;
}
81. Given an array, return an array where the each value is the
product of the next two items: E.g. [3, 4, 5] -> [20, 15, 12]
// Example usage:
const inputArray = [3, 4, 5];
const outputArray = productOfNextTwo(inputArray);
console.log(outputArray); // Output: [20, 15, 12]
Output: 3
Let me break it down for you:
3. Finally, the function returns x . Since x was passed as 3 when calling the
function (function(x){ ... })(3) , it returns 3 .
Output: 3 3 3
This might seem counterintuitive at first glance, but it's due to how JavaScript
handles closures and asynchronous execution.
Here's why:
4. The loop checks if i is still less than 3 . Since it's now 3 , the loop exits.
When the timeouts execute after their respective intervals, they access the
variable i from the outer scope. At the time of execution, i is 3 because the
loop has already finished and incremented i to 3 . So, all three timeouts log 3 .
Output: 3
Let me break it down for you:
3. Finally, the function returns x . Since x was passed as 3 when calling the
function (function(x){ ... })(3) , it returns 3 .
let c=0;
setTimeout(() => {
clearInterval(id)
},2000)
This code essentially logs the values of c at 200 milliseconds intervals until 2
seconds have passed, at which point it stops logging.
function getName1(){
console.log(this.name);
}
Object.prototype.getName2 = () =>{
console.log(this.name)
}
let personObj = {
name:"Tony",
print:getName1
}
personObj.print();
personObj.getName2();
function getName1(){
console.log(this.name);
}
Object.prototype.getName2 = () =>{
console.log(Object.getPrototypeOf(this).name);
}
let personObj = {
name:"Tony",
print:getName1
}
personObj.print();
Object.prototype.name="Steve";
personObj.getName2();
88. Can you find is there any security issue in the javascript
code?
To mitigate this security risk, you should properly sanitize or escape the data
before assigning it to innerHTML , or consider using safer alternatives like
textContent or creating DOM elements programmatically.
Here's an example of how you could sanitize the data using a library like
DOMPurify:
javascriptCopy code
const data = await fetch("api");
const div = document.getElementById("todo");
data.text().then(text => {
div.innerHTML = DOMPurify.sanitize(text);
});
console.log(eval("1 + 2")); // 3
shallowCopy[2][0] = 100;
console.log(originalArray); // Output: [1, 2, [100, 4]]
Deep copy:
A deep copy creates a new object or array that has its own copies of
the properties of the original object.
test();
2. Inside test :
undefined:
These variables are declared in the program but are not assigned
any value.
function job(){
return new Promise((resolve,reject)=>{
reject()
promise.then(()=>{
console.log("1111111111")
}).then(()=>{
console.log("22222222222")
}).catch(()=>{
console.log("3333333333")
}).then(()=>{
console.log("4444444444")
})
In this code, a Promise is created with the job function. Inside the job
1. The first then method is chained to the promise , but it is not executed
because the Promise is rejected, so the execution jumps to the catch
method.
2. The catch method catches the rejection of the Promise and executes its
callback, logging "3333333333".
3. Another then method is chained after the catch method. Despite the
previous rejection, this then method will still be executed because it's
part of the Promise chain, regardless of previous rejections or
resolutions. It logs "4444444444".
So, when you run this code, you'll see the following output:
3333333333
4444444444
var a = 1;
function data() {
if(!a) {
var a = 10;
}
console.log(a);
}
data();
console.log(a);
Explanation:
var a = 1;
function toTheMoon() {
var a; // var has function scope, hence it's declaration
if(!a) {
a = 10;
}
console.log(a); // 10 precendence will be given to local
}
toTheMoon();
console.log(a); // 1 refers to the `a` defined at the top
console.log(a == b);
console.log(a === b);
}
guessArray();
In JavaScript, when you compare two arrays using the == or === operators,
you're comparing their references, not their contents. So, even if two arrays
have the same elements, they will not be considered equal unless they refer
to the exact same object in memory.
In your guessArray function, a and b are two separate arrays with the same
elements, but they are distinct objects in memory. Therefore, a == b and a
=== bwill both return false , indicating that a and b are not the same
object.
If you want to compare the contents of the arrays, you'll need to compare
each element individually.
let a = 3;
let b = new Number(3);
let c = 3;
console.log(a == b);
console.log(a === b);
console.log(b === c);
Example :
Virtual dom
This jsx will be transpiled into javascript that interacts with the browser
when the application is built.
Now this virtual dom is compared with the original dom and creates a
changeset which will be applied on the real dom.
mounting
updating
unmounting
Mounting:
1. Constructor:
This is called right before rendering the elements into the dom.
Its a natural place to set the state object based on the initial
props.
getDerivedStateFromProps(props,state){
return { favColor: props.favColor }
}
3. render():
4. ComponentDidMount():
Updating phase:
2. ShouldComponentUpdate:
shouldComponentUpdate(){
return true/false
}
4. getSnapshotBeforeUpdate:
getSnapshotBeforeUpdate(prevProps,prevState){
console.log(prevProps,prevState)
}
5. ComponentDidUpdate:
Unmounting phase:
In this phase the component will be removed from the dom. here we
can do unsubscribe to some events or destroying the existing
dialogs etc.
1. ComponentWillUnmount:
They are used to send data from parent component to child component.
110. What are the differences between client side and server
side rendering ?
Initial Load time: csr has slow initial load time as browser needs to
interpret the data and render the page. where as ssr has faster initial
load times as server send pre-rendered html page to the browser.
Seo: Ssr is seo friendly when compared to csr as fully rendered html
content is provided to the search engine crawlers whereas csr needs to
parse javascript heavy content.
function User() {
const [message, setMessage] = useState("Welcome to React
return (
<div>
<h1>{message}</h1>
</div>
);
}
this.state = {
message: "Welcome to React world",
};
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
);
}
}
They are used to send data from parent component to child component.
Example:
// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const name = "John";
// ChildComponent.js
import React from 'react';
function ChildComponent(props) {
return (
<div>
<h2>Child Component</h2>
<p>Hello, {props.name}!</p>
</div>
);
}
State is used to hold the data of a component whereas props are used
to send data from one component to another component.
Reduced maintainability:
Prop drilling can also make code less maintainable. This is because if a
prop needs to be changed, the change needs to be propagated through
all of the components that use it. This can be a time-consuming and
error-prone process.
Performance overhead:
Prop drilling can also have a performance overhead. This is because
every time a prop is passed down to a component, the component
needs to re-render. This can be a significant performance overhead in
large applications with many components.
Advantage:
Reference: https://react.dev/reference/react/PureComponent
they are helpful when we want to update the component whith out
using state and props and prevents triggering rerender.
Common useCases:
Media control/Playback
Examples:
1. Managing input focus
function App() {
const inputRef = useRef();
return (
<div>
<input type='text' ref={inputRef} />
<button onClick={focusOnInput}>Click Me</button>
</div>
);
}
function App() {
const audioRef = useRef();
return (
<div>
<audio
ref={audioRef}
type='audio/mp3'
Reference: https://www.memberstack.com/blog/react-refs
Example:
2. Using the Forward Ref Component: Use this component and pass a ref
to it.
function ParentComponent() {
const inputRef = useRef(null);
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallba
return { hasError: true };
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return this.props.fallback;
}
return this.props.children;
}
}
Then you can wrap a part of your component tree with it:
Uncontrolled components:
react will use this to indentify, which elements in the list have been
added, removed or updated.
function MyComponent() {
const items = [
{ id: 1, name: "apple" },
{ id: 2, name: "banana" },
{ id: 3, name: "orange" }
];
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
}
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
Eg:
Fetch data
https://react.dev/learn/reusing-logic-with-custom-hooks
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
setData(result);
} catch (error) {
setError(error);
} finally {
setLoading(false);
fetchData();
// Cleanup function
return () => {
// Cleanup logic if needed
};
}, [url]); // Dependency array to watch for changes in t
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
{data && (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)}
</div>
);
}
// Initial state
const initialState = {
count: 0
};
// Reducer function
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};
// Component
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment'
<button onClick={() => dispatch({ type: 'decrement'
</div>
);
};
// Create a context
const UserContext = createContext();
return (
<UserContext.Provider value={{ user, login, logout }}>
{children}
</UserContext.Provider>
);
};
// Example usage
const App = () => {
return (
<UserProvider>
<Content />
</UserProvider>
);
};
return (
<div>
{user ? (
<div>
<p>Welcome, {user.username}!</p>
<button onClick={handleLogout}>Logout</button>
</div>
) : (
<div>
<p>Please login</p>
<button onClick={handleLogin}>Login</button>
</div>
)}
</div>
);
};
useEffect(()=>{
console.log("Called on initial mount only once")
},[])
useEffect(()=>{
console.log("Called on every dependency update")
This will be called whenever dependency value changes (here Eg: isFeature
or content).
useEffect(()=>{
return ()=>{
console.log("Any cleanup activities/unsubscribing e
}
})
===========================================================
// Enabling strict mode for entire App.
===========================================================
===========================================================
// Any part of your app
===========================================================
function App() {
return (
<>
<Header />
<StrictMode>
<main>
<Sidebar />
<Content />
</main>
</StrictMode>
<Footer />
</>
);
}
136. What are the different ways to pass data from child
component to parent component in react ?
There are 4 common ways to send data from child component to parent
component. They are.,
1. Callback Functions
2. Context API
When an event occurs in the child component (like a button click), call
this function with the data to be passed to the parent.
Parent Component:
function ParentComponent() {
const [dataFromChild, setDataFromChild] = useState('');
return (
<div>
<ChildComponent onData={handleDataFromChild} />
<p>Data from child: {dataFromChild}</p>
</div>
);
}
Child Component:
return (
<button onClick={sendDataToParent}>Send Data to Parent<
);
}
It will not trigger any event by itself whenever the data is updated.
Parent component:
return (
<>
<TextEditor valueRef={valueRef} />
<button onClick={() => console.log(valueRef.current)
</>
Child component:
Optimize rendering with keys: Ensure each list item in a mapped array
has a unique and stable key prop to optimize rendering performance.