React-Interview- ROCK (17.1v)

Devesh Kr Sri
109 min readMar 10, 2021

https://medium.com/react-bootcamp — many react tutorial

REDUX PAGE LINE — https://devesh-kr-sri.medium.com/react-redux-e8300c2f841b

css-moduless

Rode Map to Frontend2:58

How the internet works? 3:25

HTML 3:52

Code Editor 4:13

CSS 4:37

JavaScript 5:35

Version Control Systems

( Git) 5:48

Github 6:05

Package Managers 6:26

Bootstrap 6:37 SASS 6:59

React, Vue or Angular 7:16 Tailwind CSS 7:55 Byte (front end tooling solution)

8:18 JS testing tools (Jest, Cypress)

8:42 Typescript 9:21

OWASP 9:29

Restful API 9:39 GraphQL 9:58

Next.js 10:15 Astro 10:43

optimization and efficiency 10:55

Google Lighthouse

11:03 React Native

How To Become a SENIOR React Engineer

REACT BASIC TUTORAILS
https://www.youtube.com/watch?v=7DCIm

Best Frontend Challen Youtube
https://www.frontendplanet.com/best-youtube-channels-frontend/

Javascript stackblitz: react-interview-demo
https://stackblitz.com/edit/react-interview-demo-ntbvws?file=src%2FCustomHooks.js,src%2FForm%2FHooksForm.js,src%2Findex.js,src%2FfetchCurdAPI.js,src%2FLoginUseReducerImmer.js

MAXMULAR
https://github.com/academind/react-complete-guide-code/commits/06-styling/code/05-styled-components-dynamic-props/src

Q1: What is React?

  1. React is an open-source JavaScript library
  2. Developed Facebook for building complex
  3. Can build interactive UIs in web and mobile applications.
  4. It’s component-based, all the components are reusable.
  5. Single Page Application and uni-directional
  6. React’s core purpose is to build UI components; it is often referred to as just the “V” (View) in an “MVC” architecture.

React is component-based Architecture, which means that components are the building block of the react framework. These help to build an interface and can use reusable.

// Normal Function
export default function FetchAxus() {
return (
<></>
)
}


// Arrow function
const FetchAxusArro=()=> {
return (
<></>
)
}

export default FetchAxusArro;

🔗 Source: codementor.io

Next.js, clinet side rendering vs cerverside rendering

Client-side rendering (CSR) and server-side rendering (SSR) are two different approaches to rendering web pages, and they have implications for the initial page load, performance, and user experience. React is a JavaScript library for building user interfaces, and Next.js is a popular React framework that provides tools and conventions for server-side rendering among other features.

Client-Side Rendering (CSR):

  1. Initial Render:
  • In CSR, the initial HTML is generated by the browser, and the page is mostly empty until the JavaScript bundle is downloaded and executed.
  • The browser downloads the JavaScript bundle, parses it, and then renders the content on the client side

2. Page Loading:

  • Faster initial page load, as only the HTML and a minimal amount of JavaScript are sent from the server.
  • The client browser takes care of rendering the page, which can result in a more dynamic and interactive experience after the initial load.

3. SEO Challenges: Search engine optimization (SEO) can be a challenge, as search engine crawlers may not execute JavaScript and might not see the fully rendered content.

4. User Experience: A potential for slower time to content, especially on slower network connections or less powerful devices, as the browser has to wait for the JavaScript to be downloaded and executed before rendering the page

Server-Side Rendering (SSR) with Next.js:

  1. Initial Render: In SSR, the initial HTML is generated on the server and sent to the client. This means that the client receives a fully rendered page from the server.

2. Page Loading:

  • Slower initial page load compared to CSR, as the server needs to generate the HTML for each request.
  • Provides a better experience for users with slower network connections or less powerful devices, as they get a fully rendered page without waiting for JavaScript to be downloaded and executed.

3. SEO Benefits: Better for SEO, as search engine crawlers receive a fully rendered HTML page, ensuring that the content is indexed and ranked appropriately.

4. User Experience: Generally provides a faster time to content, especially for users with slower connections, as the server sends a fully rendered page.

Hybrid Approaches:

  1. Next.js Hybrid Rendering:
  • Next.js supports a hybrid approach where certain pages can be statically generated at build time (Static Site Generation — SSG), while others are server-rendered on each request (Server-Side Rendering — SSR).
  • This allows developers to choose the rendering strategy based on the specific needs of each page.

In summary, the choice between client-side rendering and server-side rendering depends on factors such as SEO requirements, initial page load speed, and the desired user experience. Next.js provides flexibility by supporting both server-side rendering and static site generation, allowing developers to choose the most appropriate approach for different parts of their applications.

JSX: JAVASCRIPT INTO XML, SYNTATACTICALLY SUGAR FOR CREATEELEMENT
IN JAVASCRIPT YOU CAN WRITE CREATEELEMENT, APPENDCHILD AND CREATE PAGE
BUT JSX IN REACT HELP TO DO THE SMAE THING.
BEBEL: COMPILE JSX INTO JAVASCRIPT
PROPS: ARE PROPERTY, TRANSFER DATE FROM 1 COMPN TO ANOTHER, READ ONLY,
PERAIMETER IN FUNCTION ARE PROP IN REACT.
STATE: WE CANT UPDATE ANY VARIABLE IN REACT AND SHOW ON THE PAGE,
sO WE USE USE useSTATE()
useEffect: update side effect task in function component, function like timmer
i.e setInterval(), setTimeout(), or DOM update or fetch from API.
useEffect(() =>... ) always run
useEffect(() =>... ,[]) run only first time, but not after click on button
useEffect(() =>...[count]) run on change of count i.e setCount(count+1)
Ex: https://stackblitz.com/edit/react-ts-uzzfbd?file=App.tsx

useRef: Manuplate DOM directly

DATAFLOW: UNIDIRECTIONAL, TOP TO BOTTOM, WITH PROPS AND STATE, GLOBALE
STATE-MANAGEMENT, HOW DATA SHARED DEEP 10 LEVEL ( PROP-DRILLING )
CONTEXT API >> useContext >> REDUX >> USEREDUCER.
useState() MANAGE DATE LOCALLY, GLOBALLY, we use
1. REDUX,
2. CONTEXT,
3. useReducer()

REQUEST-FROM-API-BEFORE RENDER- COMPONENTDIDMOUNT, LIFECYCLE TALK, IN HOOKS
USEEFFECT WITH NULL ARGUMENTS FOR COMPOENETDIDMOUNT
CONDITIONAL-RENDRING: TERNANRY OPERATION
DOM - Its an api for html an xml, which defind the structure to modify it.
SHADOW DOM VS VIRTUAL DOM


JAVASCRIPT:
1. HOISTING
2. PROMISE
3. ARROW FUCTION
4. AYNC PROFRAMMING
5. PROTOTYPE
6. CORS
7. AXIOUS/FETCH
8. MEMORIZATION - MEMO/CALLBACK
9. HIGHLEVEL DESING AND LOW LEVEL DESING / ARECTURE
10. KEYS
11. PRACTICAL - SEARCH LIKE WORK D
12. REDUX - ITS PRIDICABLE STATE CONTINER FOR JAVASCRIPT LIBRANRY
MEANS REDUX LIBRARY CAN BE USED WITH ANY JS APPLICTION
LIKE REACT/ANGULAR
IT LIKE A STAE CONTINER
HELP TO SOLVE PROP DRILLING WITH GLOBAL STATE

STORE/REDUCER/ACTION
STORE - HOLD STATE OF APPLICATION
OBJECT LIKE FIRSTNAME/AGE IN THE PAGE
STATE = [FIRSTNAME:"JOHN", AGE:30 ]
REDUCER - GET STORE AND RETURN STORE WITH CALCULATION
ACTION - DESCRIPT CHANGE IN STATE OF APPLICATION, EVENT ON THE PAGE
13. DEBUGGIN/THROUGHLING
14. DSA QUESTION ON LINK/QUEUE/SET/MAP
15. Memory management -
memo - used in javascript for memory management
memo - used in react to memorize the component function
useMemo - used in react to momorize function
useCallback - momorize the
16. REACT FORM - DEFAULT HTML FORM BEHAVIOUR IS ON SUBMIT IT WILL TAKE
TO NEXT PAGE. IN REACT IT WILL BE ON THE SAME PAGE AND THEN WE
CAN DATA OR DO VALIDATION i.e <form onSubmit=[formSubmit]> ,
17. key problem : each child in list should have key element
each list should have a key element. Key help to identify
which elements have been added updated or deleted. Key gives the
element a stable identity.
18. useReducer -

>> Simmiler to useState,
>> If number/string/boolean use useState, for Array/object useRecuer
>> Manage 1 or 2 state use useState, for 5+ states useReducer
>> Simple purpose use useState, for complex logix useRedcuer.
Its more predictable and manageblae.
>> Manage local state useState, but for globel stateuseReducer



Ex:
const [state, dispatch] = useReducer(loginReducer, initialState);
<button onClick=''() => dispatch({ type: 'logOut' })''> Log</button>

19. e.preventDefault(); onSubmit from submit - when we dont do every
time we click button. Page get submit and nevigate to self page
due to default form property. THIS STOP IT.
20. Statemenagement - Redux, context, Hooks(useReducer,useState),
Caching(
GraphQL, react-query)
https://leerob.io/blog/react-state-management
https://www.youtube.com/watch?v=u_o09PD_qAs

NODE:
PM2 - LOG ON THE PRODUCTION SERVER - PROCESS MANAGER- START SERVER WITH CHNAGE

Q1 ; Can we use React in Angular - yes, react is libray and Angular
is framework
and framework can have many library.
Q2 : Use of profile - TO check the performace of react, how much the
componet have renders and which one.
Q3 : Do react js follow MVC? No, since react only use the view.
Q4 : Why React JS fast? Due to virtual DOM.
Q5: useID hook? use to genrate unique ID, like array ittrate, or list
Q6: React strict-more and Javascrict strict-mode? Use React.strict-mode, both
are used for warning, unsafe, depricited code. Only work in dvelopment mode.
This apply on specific compoment and full component.
KRIS.. INTERVIEW
Tailwind/Spotify/Material UI
> TAILWIND - https://www.youtube.com/watch?v=L2KHCWJ3gjs
> CAN BE USED WITH NEXT.JS, GATSBY, CREATE-REACT-APP
> INSTALL TAILWIND CSS/POST CSS / CRAKO LIBRARY AND CHANGES TO REACT SCRIPT

Css/HTML5
REDUX - CHANGED
Next.js/Vue
Testing - react testing libra/cyprus

Practical:
Question -
Screenshare coding
Javascript-
Environment setup
Typescript
Graphql - naming /folder star/ type
Curd operation


HOW MANY DAYS COME TO OFFICE ? 1/2 MONTH
SEQURITY :
TOKEN
CORS
PM2
GRAPHQL

BoxModel - margin/border/padding/item
Local Storage

JRPC/AXIOC/FETCH/GRAPHQL

TESTING IN PROJECT
REDUX - PRINT AND TELL

Upgraid React:
> "react": "^17.0.2",
> "react-dom": "^17.0.2",
> "@types/react": "^16.9.34",
> "@types/react-dom": "^17.0.2",
> "@types/styled-components": "5.1.26",
or any other dependent library, after this test app.

CORS: fixing cors issue
Use below plugin to fix it.
https://chromewebstore.google.com/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf

use cors proxy.io
fetch(“https://corsproxy.io/?https://www.abc.com")

— — — — History — — — — →

window.history.back();
window.history.forward(); //Create a forward button on a page (This example will not work if the next page does not exist in the history list):
window.history.go(-2); //Click on the button to go back two pages:
var x = history.length; //Get the number of URLs in the history list:



Immer
https://immerjs.github.io/immer/
Mutable/immutable
Help to change the value of state without changing the original object.
And remove complexity ..obj -> .obj, make the obj immutable
Example - https://www.youtube.com/watch?v=yYHMGin0EMk
https://www.youtube.com/watch?v=4EXFBNRqS6U

import produce from 'immer'

case 'SET_DISPLAY_NAME':
if (typeof displayName === 'undefined') return state
// if (!startDate || !endDate) return state
return produce(state, (draft) => {
draft.displayName = displayName
draft.frequencyCap = {}
})

return produce(state, (draft) => {
draft.performanceGoal = {
performanceGoalType,
}
draft.budget = state.budget || {}
const dtStartDate = new Date(startDate)
draft.budget.budgetSegments.dateRange = {
startDate: fromDateToDVDate(dtStartDate) as RTD_YT.Date,
}

const { pacing } = draft //delete
if (pacing?.pacingPeriod === 'Flight') {
delete draft.pacing.dailyMaxMicros
}
})

Problem with JS
const obj {
anotherProp: 'string',
anotherObj :{
anotherObject:{
a:5
}
}

Copy the object with out modify the original and change a:6

const obj2 {
...obj,
anotherObj :{
...obj.anotherObj,
anotherObject:{
...anotherObject,
a:6
}
}

log(obj, obj1)

FIX with immer (simple):
immper.produce(obj, draft =>{
draft.anotherObj.anotherObject = 6,
draft.anotherObj.modifySomeProp = "hello"
}


__________________________________
Session 2


Const state :{
todos:[{
text:"Buy milk",
completed:false
},
{
'text:"Buy Egg",
'completed:true
}
]
};
What frontend Designer does?

Udpate: toggle:
toggleCompleted = index =>{
const newTodos = this.state.todos.map((todo,i)=>{
if(index==I){
return {
...todo,
completed: !todo.completed
}
}
return todo;
}
}

setState(newTodos)

With dimmer: making google
const newTodos = produce(this.state.todos, draftState =>{
draftState[index]["completed"] = !draftState[index]["completed"]
})

DELETE:
deletetodostate = index =>{
const newTodos = this.state.todos.filter((todo,i)=>{
if(index==i){
return false
}
return true;

return index===i ? false :true

})
setState(newTodos)
}

//with immer
const newTodos = produce(this.state.todos, draftState =>{
draftState.splice(index,1)
})
setState(newTodos)
}

Modify
modifytodostate = (index, newText) =>{
const newTodos = this.state.todos.map((todo,i)=>{
if(index==i){
return {
...todo,
Text: newText
}
}
return todo;
}
setState(newTodos)
}

//with immer
const newTodos = produce(this.state.todos, draftState =>{
draftState[index]['text'] = newText;
})
setState(newTodos)
}

Add
addtodostate = (newText) =>{
const newTodos = this.state.todos.concat({text})
setState(newTodos)
}

//with immer
const newTodos = produce(this.state.todos, draftState =>{
draftState.push({newText});
})
setState(newTodos)
}




Ritik Raj
1 month ago
1.What are sematic tags
2.Position relative and postion absolute
3.What is flexbox - display property, design layout in horizontal,
justify content
4.What is boxModel - content-padding-border-margin, space between element
5.What is Eventloop - Machanism do work as Asyncs programming, Js is single
thread, but with smart datastructur, it give the
issue of multithread.
Eventloop has one simple job - to monitor call stack and callback queue or
message queue.
If the call stack is empty then it will take first callback from callback
queue and post to call stack to run.
Console.log("hi")
setTimeout(()=>{
Console.log("Execute Immediately");
},0);
Console.log("bye")
Result // hi, bye, Execute Immediately

Callback queue ----(eventloop)--> call stack(console.log) ->
WebAPI(setTimeout/dom/fetch) -> Callback queue
Promise vs setTimeout(0) - promise, high priory micro takes
6.What is DOM
7.What is Hoisting - var diff from const, before running the code we have
assigned memory to all the function and variables, var hosted in global
variable and let/conted hosted in saperted memory case, we cannot access
it also set to temopary dead soon, until we initialize value we cannot
access and get error. Function expression and arrow function are not hosted.
8.What is closure: function bunded together with ref to his lexical scope.
Inner Function amino have access to variable to outfunctino. Even out
function returned. It uses the stack memory to get the access to outer
functinn. Innerfuncation remembers in memory even the parent are present.
9.What is Callback Hell - multiple callback, every next taking argument
from previous and grow horizontally. Difficult to debug.
10.How many argument hold Promise - resolve/reject
Promise object can be:Pending, FulfilledRejected
The Promise object supports two properties: state and result.

11.What is Map, Filter And Reduce - HOC in Javascript as they take
another function are the argument in JS.map ittrate and do some operation,
input/output array and length output same, filter element bassoon on
condition, equal or less value, reduce return single value
12.How many scopes are in Javascript - global, local, function and block
13.What is Call,Apply and Bind - it help to do function borrowing, we can
borrow function and use the data from other object and use the data of
some other object. Call takes 2 arguments, 1st is reference, argument to
function, apply is same as call, but later argument takes in the form of
array, but in calll we need to pass the argument expedite, Bind same as
call, difference instead of just immediate invoking the function it returns
the copy of the function. Which we can invoke later in our code.
14.What is This Keyword - refer to object, which object refer it depends.
Console.log - global, inside fun- glob la, strict mode- inside fucntin o
give undefined.
15.What is Diffrence b/w Normal function & Arrow Function : arrow allow
write sorter fuction, not hosted like reg fun., arrow loose this, define
to the arrow, cannot used constror in arrow funcation.
16.What is Memoization: storing the return value in casched value, avoid
rerendeing issue, help perform optimisation.
17.What is spread Operator and Rest Operator
18.O/p question (spread operator with object)
19.O/p Question (Based on Promise)
20 .O/P Quesiton (Based on In and Of)
21.What is virtual DOM reconciliation
22.Advantage of ReactJs - virtual Dom, easy jsx no external file, easy
parts to child, single place, easy to lean for bigger
23.What is one-way DataBinding - top to Botton not form child to parent,
useContext, redux, useReeducer
24.How Redux work - action{type, payload)->
reducer(state, action-> store->back to page to get and dispatch
25.What is Higher Order Component - function to write again and again,
takes the funcation as argument, do the functional to return as new component.
Reusable code.

27.How do you handle lifecycle method in functional component

Question
// array to object
const arr = [10,20,30,[10,20]]
const obj = {...arr}
console.log(obj)
Ans: (3) {0: 10, 1: 20, 2: 30}



// object to array
const obj1 = {name:'abc', city:"london",

address:{line:"90", postcode:"sn12aj"}}
const arr = Object.entries(obj1)
console.log(arr)


// promise
// const myPromise = new Promise((resolve,reject)=>resolve(2));
const myPromise = new Promise((resolve,reject)=>{
setTimeout(()=>{
if (100/2){
resolve(2)
}else{
reject()
}
},5000)
});

myPromise
.then((value) => {
console.log(`${value} and bar1`)
return value *2
})
.then((value) => {
console.log(`${value} and bar2`)
return value *2
// console.log(value);
})
.then((value) => {
console.log(`${value} and bar3`)
return 0
})
.then((value) => {
console.log(`${value} and bar4`)
})
.catch((err) => {
console.error("Error",err);
})
.finally((value) => {
console.log('Experiment completed', value); //the value will be undefined,
// as it don't receive any value
// and also its is always at the bottom
});


//ouyput
2 and bar1
4 and bar2
8 and bar3
0 and bar4
Experiment completed undefined

const arr = [10,20,30]
for(let i in arr){
console.log(i) //0,1,23
}

arr.foo = "hi"
for(let i in arr){
console.log(i) // hi
}













What is react unique ?
React is framework not an library so you can use your own stack to build application
Work on Virtucal DOM
View irented — show how to view
Uni-directional — one direction
Component based — Reusabllity with state and manage state

What is virtual DOM?
Copy of real dom, any change is first done on the virtual dom and then do the comparation.
with real dom and make the only change to real dom and this is concept of reconcilation.
This make the application fast and quick responsive.Diffing algorithm running that check the
chnages also reconcilcation
* useRef update the value directly on real dom. ex. like focus, current.value

Props/state
Props read only property and flow form parent to child.
State are internal to the component. Change in state will change in component.
You can pass both the state and props as parameter.

Diffrence between server side and client side rendring?
Whole application can render on server side form node, makes is faster and SEO friendly.
Content heavy site should use server side rendering.
Client side application or APP — outlook, teams, slack, figma
Server side rendering for data heavy website like Amaxon, flip cart.

What is “React Fiber”?
This came after React 16 and help to run the application faster.
It re-write the core algorithm to run the application to handle small small part of application to run individually.

What are synthetic event in react?
diffrent browser does event management in diffrent ways. react.jquery work on each borwser with same API.
No need to write diffrent query for diffrent browser. THis is done with event delegation, when you click button
insted on going to brower it goes to react. This is why its called synthetic event. It have all the common event. Like \
event.target etc.

Hooks why?
Reusable
State logic is testable
Hooks is testaible
Now become functional based due to this.

SHADOW DOM VS VIRTUAL DOM


// SHADOW DOM
Story, when we open the brower, it create a DOM tree, (html)
Inside that Main DOM there is hidden Shadow DOM, any change to css,element
ot the main DOM will not change the Shadow DOM.

// https://javascript.info/shadow-dom

// >>>>WHAT IS THE NEED?
When we use the external library like bootstrap, some time css match,
which then overrede the DOM. Example when using multiple library,
Ex: normal html color change
<style>
.error {
color:'red';
}
<bootstrap css {
.error {
color:'blue';
}
</style>

<p class={error}> This is color</p>


// >>>> how to check Shadow DOM
<input type="range" />
when we open in browser, it shows many css like blue color, rounded etc.
inspect F12, and see, see there is checkbox to see shadow dom.
Setting>prefrence>Show user agent shadow DOM.

// How to create Shadow DOM?
<!doctype html>
<body>
<script>
customElements.define('show-hello', class extends HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = `<p>
Hello, ${this.getAttribute('name')}
</p>`;
}
});
</script>

<show-hello name="John"></show-hello>
</body>

Q2: What are the advantages of ReactJS?

Below are the advantages of ReactJS:

  1. Increases the application’s performance with Virtual DOM
  2. JSX makes code is easy to read and write
  3. It renders both on client and server side
  4. Follows Unidirectional data flow or data binding
  5. Uses reusable/composable UI components to develop the view
  6. Easy to integrate with other frameworks (Angular, BackboneJS) since it is only a view library
  7. Easy to write UI Test cases and integration with tools such as JEST.
  8. SEO-friendly. React presents the first-load experience by server-side rendering and connecting event-handlers on the side of the user

🔗 Source: github.com/sudheerj

Q3: What are the limitation of ReactJS?

Below are the limitation of ReactJS:

  1. Not a full framework i.e its just the view. ReactJS Covers only the UI Layers of the app. So you still need to choose some other technologies to get a complete tooling set for development in the project.
  2. Library is quite large
  3. Difficult to understant for the novice programer
  4. Use inline tamplate and JSX.
  5. Poor Documentation : React technologies updating and accelerating so fast that there is no time to make proper documentation.
  6. There is a learning curve for beginners who are new to web development.
  7. The code complexity increases with inline templating and JSX.
  8. Too many smaller components leading to over-engineering or boilerplate
  9. No In-build library line services, routing, most library are 3rd part.

🔗 Source: https://github.com/sudheerj

Q4: What is virtual DOM?

Lightweight Javascrit object which is the copy of the real DOM

The virtual DOM (VDOM) is an in-memory representation of Real DOM.

IT WORKS IN 3 STEPS:

  1. Whenever the underlying data changes, the entire UI is re-rendered in Virtual DOM representation.
  2. Then the difference between the previous DOM representation and the new DOM is calculated.
  3. Once the calculations are done, the real DOM will be updated with only the things that have actually changed.

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.

🔗 Source: github.com/sudheerj


+---+----------+------+
| | A | B |
+---+----------+------+
| 1 | Col1 | Col3 |
| 2 | Value 1 | 123 |
| 3 | Separate | |
| 4 | | |
+---+----------+------+

Q5. Why browsers can’t read JSX (JavaScript XML)?

because JSX files need to convert to javascript with the help of JSX transformer.

  1. JSX is not a regular JavaScript
  2. The browser can read JavaScript objects only.
  3. JSX file is converted to JS object by JSX Transformer like Bebel, before reaching Brower
Bible does the changes. Convert React Es5 to Es6?
Es5 — React.createClass{…}
Es6 — React.Component{..}

Q7: What are the web worker?

Web Workers in React can be used to perform tasks concurrently in a separate thread, preventing them from blocking the main thread and improving the overall performance of your application. Here’s a simple example of how you can use a Web Worker in a React application, UI Freez:

export default function WebWorker() {const handleSubmit = () =>{
let final = 0;
for (let i=0; i<10000000000000;i++){
final += i;
}
console.log(final)
}
const handleWorkerSubmit = (e) =>{
const myWorker = new Worker('worker.js')
myWorker.postMessage("do work");
myWorker.onmessage = function(e){
console.log(e.data)
}
}
return (
<div> <button onClick={handleSubmit} >Submit</button>
<button onClick={handleWorkerSubmit}>Submit worker</button> </div>
)}worker have postMessage/slef worker.js
onmessage = function(e){let final = 0;
for (let i=0; i<10000000000000;i++){
final += i;
}
console.log("my", final)
postMessage(final);
}

7. What is a SyntheticEvent in React?

In React, the SyntheticEvent is a cross-browser wrapper around the native browser events. It's designed to provide a consistent interface for handling events in React applications, regardless of the differences in the underlying browser implementations.

SyntheticEvent is a cross-browser wrapper around the browser’s native event. It has the same API as its browser’s native counterpart, including methods like stopPropagation() and preventDefault(). However, unlike the browser’s native events, SyntheticEvent works identically across all browsers.

Here are some key points about SyntheticEvent in React:

  1. Cross-browser Compatibility:
  • React normalizes event handling across different browsers. This means that you don’t have to worry about browser-specific quirks when working with events in React.

2. Event Pooling:

  • React uses a technique called event pooling to improve performance. When an event is handled, the SyntheticEvent object is reused and all its properties are nullified after the event handler has been called. This allows React to recycle these objects and reduce memory usage.

3. Properties and Methods

  • SyntheticEvent has properties and methods similar to those of native browser events. You can access properties such as target, currentTarget, type, etc., just like you would with native events.

4. Asynchronous Event Handling:

  • React may handle events asynchronously for performance reasons. This means that the properties of SyntheticEvent may be nullified after the event handler has been executed. If you need to access event properties asynchronously, you can call event.persist() to remove the event from the pool and ensure that its properties are retained.

5. Usage in React Components:

  • When working with events in React components, you typically define event handlers using arrow functions or class methods. For example:
import React from 'react';

class MyComponent extends React.Component {
handleClick = (event) => {
console.log(event.target.value);
};

render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}

export default MyComponent;
  • In this example, the handleClick method is an event handler for the button's click event, and it receives a SyntheticEvent object as its parameter

Remember that, in most cases, you can treat SyntheticEvent objects in a similar way to native browser events. However, keep in mind the event pooling and the potential for asynchronous behavior, especially if you need to access event properties later in your code.

8. How to conditionally apply class attributes?

Similar to hiding and displaying an element, sometimes, we also need to conditionally apply styling to our element. Typically syles are applied via classes instead of directly setting it on the element. An interviewer might ask this question to understand the candidate’s familiarity with using conditionals in React and how they can be applied to class attributes.

React lets you include conditionals such as && and ternary operators to conditionally display parts of your component. The same concept can be applied to classNames.

The snippet below uses a ternary operator to add the disabled class when the disabled prop is true and the default class if it’s false.


const [favColor, setFavColor] = useState('blue');

<thead className={'App' + (favColor === 'blue' ? 'Blue' : 'Green')}>

css:
.App {
background-color: antiquewhite;
}

.AppBlue {
background-color: blue;
}

.AppGreen {
background-color: green;
}

Link :https://stackblitz.com/edit/react-ts-uzzfbd?file=App.tsx&file=style.css
<div 
className={'btn-panel ' + (this.props.disabled ? 'disabled' : 'default')}>

Q8: What is the difference between a Presentational component and a Container component?

or Stateless or Statefull?

or functional or class componets

  • Presentational components are concerned with how things look. They generally receive data and callbacks exclusively via props. These components rarely have their own state, but when they do it generally concerns UI state, as opposed to data state.
  • Container components are more concerned with how things work. These components provide the data and behavior to presentational or other container components. They call Flux actions and provide these as callbacks to the presentational components. They are also often stateful as they serve as data sources.

🔗 Source: github.com/Pau1fitz

Q9: What is state in ReactJS?

State of a component is an object that holds some information that may change over the lifetime of the component. We should always try to make our state as simple as possible and minimize the number of stateful components.

Let’s create user component with message state:

class User extends React.Component {
constructor(props) {
super(props);
this.state = {
message: "Welcome to React world",
}
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
);
}
}
New Version:
const [message, setMesssage] = useState("")

if we dont call the super in constructor we can use this.state error ‘ReferenceError: Must call super constructor in derived class before accessing ‘this’ or returning from derived constructor

🔗 Source: https://github.com/sudheerj

Q10: What is the difference between state and props?

Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to component. i.e,

Props

  • Props get passed to the component similar to function parameters, Handled by props, can’t change it.
  • Props in functional component use only ‘’props”’,
  • props in-class component use this: ‘’this.state’’ and ‘’this.props’’
  • ****In Short can be called as properties, Are read-only, Are pure i.e immutable, Always passed down from parents to child components, Used to render dynamic data.****

Changing Props Value by going back to the parent component and asking to change the child component.

State

useState — example of state, or this.state

  • setState() — The state values can be changed with the help of setState().

How setState works?
setState helps to rerender the code and setState calls the call back and take the previous state and return the new state.

  • ****Heart of reacts components Must be kept as simple as possible, Determines components rendering and behavior, Creates dynamic and interactive components, It is accessed via this.state(), Can be updated using this.setState()****

Examaple
1. State in Class


this.state = { message: '' }
this.setState({message: 'Hello World'}); //componentdidmount call

render () {
const {message} = this.state

return (
{message} or {this.state.message}
{this.props.name} //in case of props
)
)

2. Hooks useState
const [name, setName] = useState({name:''})

setName('CountryName') -> when only 1 time changes
setName((e)=>e:'CountryName') -> multiple time chnges

return (
{name}
)

Hooks useState

UPDATE useState():

--->With Object

at 1 and 2, First, Make the copy with spread Operation and update the value
setValues({…values, last name:”Raj”})

--->Example

//Syntax : update object
//https://stackblitz.com/edit/react-ts-uzzfbd?file=App.tsx&file=style.css
setUser((p)=>({...p, age:p.age+1}))
setUser((p)=>{
return {...p, age:p.age+1}
})

--------------------------------------------------
function UseStateArray() {
const [values, setValues] = React.useState({
language: "",
yearsExperience: 0,
isEmployed: false,
});

function handleClick(event) {
setValues({...values, language:"HINDI"}) //1


setValues((prevState) => { //2
return { ...prevState, isEmployed: !prevState.isEmployed };
// It is essential to return the new state from this function

});
}
return (
<button onClick={handleClick}>Change State</button>
);
}

3 type to do?
Note - here we are not updating the state but copying the
last state and creating new one

// setTodo([{id:Math.random(), color:text}]) //1

//second best option, store value
// setTodo([...todos, {id:Math.random(), color:text}])

//best option,, store value
// setTodo(prevTodo=>[...prevTodo, {id:Math.random(), color:text}])
Updating/adding :  STATE WITH OBJECT

import React, { useState, useEffect } from 'react';

export default function UseStateObject() {
const [values, setValues] = useState([]);

function handleClick(event) {
// update state with new values in id and value
setValues([
...values,
{
id: values.length,
value: Math.random(),
},
]);
}
console.log('value :', JSON.stringify(values));
return (
<>
<button onClick={handleClick}>Change State</button>
<p>{JSON.stringify(values)}</p>
</>
);
}

🔗

Source: https://github.com/sudheerj

1. Basic Usage:

import React, { useState } from 'react';

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

// Change state using the updater function
const increment = () => {
setCount(count + 1);
};

return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}

2. Functional Update:

You can use a function as an argument to setCount, which receives the current state value and returns the new state value. This is useful when the new state depends on the current state.

const incrementByTwo = () => {
setCount((prevCount) => prevCount + 2);
};

3. Conditional Update:

Perform a state update conditionally based on the current state or other variables.

const incrementIfEven = () => {
if (count % 2 === 0) {
setCount(count + 1);
}
};

4. Batching State Updates:

React batches state updates for performance. If you want to perform multiple state updates in sequence, you can use the functional update form to ensure you are working with the latest state.

const handleMultipleUpdates = () => {
setCount((prevCount) => prevCount + 1);
setCount((prevCount) => prevCount + 1);
};

5. Object State:

When dealing with state objects, you need to spread the previous state to avoid overwriting other properties.

const [user, setUser] = useState({ name: 'John', age: 25 });

const updateAge = () => {
setUser((prevUser) => ({ ...prevUser, age: prevUser.age + 1 }));
};

6. Toggle State:

Toggle between different states.

const [isVisible, setIsVisible] = useState(true);

const toggleVisibility = () => {
setIsVisible(!isVisible);
};

Example of above

https://stackblitz.com/edit/react-ts-uzzfbd?file=App.tsx,practice_javascript.ts,useCalback2.tsx,useMamo1.tsx

// import * as React from 'react';
import React, { useState, useEffect } from 'react';
import './style.css';
[[[
.App {
background-color: antiquewhite;
}

.AppBlue {
background-color: blue;
}

.AppGreen {
background-color: green;
}
]]]

interface User {
id: number;
name: string;
username: string;
email: string;
}

export default function App() {
const [list, setList] = useState<User[]>([]);
const [count, setCount] = useState(0);
const [favColor, setFavColor] = useState('red');
const [lan, setLanValues] = React.useState({
language: '',
yearsExperience: 0,
isEmployed: false,
});
const [user, setUser] = useState({ name: 'John', age: 25 });
const [open, setOpen] = useState(false);


useEffect(() => {
console.log('COUNT - 1');
}); //always run

useEffect(() => {
console.log('COUNT - 2');
}, []); ///run only first time, but not after click on button

useEffect(() => {
console.log('COUNT - 3');
}, [count]); //run on change of count i.e setCount(count+1)

useEffect(() => {
get();
}, []);

const get = async (): void => {
await fetch('https://jsonplaceholder.typicode.com/users')
.then((res) => res.json())
.then((result) => setList(result));

// axios
// .get<User[]>('https://jsonplaceholder.typicode.com/users')
// .then((response) => {
// setList(response.data);
// })
// .catch((error) => {
// console.log(error);
// });
};

const onSubmit = () => {
setCount(count + 1);
};

//1. Basic update:
const onChangeColor = () => {
setFavColor('Green'); // single update
};

//2. Functional Update: which receives the current state value and returns the new state value.
//This is useful when the new state depends on the current state.
const onChangeCount2 = () => {
setCount((prevCount) => prevCount + 2); // no {}, as no object and single valye
};

//3. Batching State Updates: perform multiple state updates in sequence, you can use the functional update form to ensure you are working with the latest state.
const handleMultipleUpdates = () => {
setCount((prevCount) => prevCount + 1);
setCount((prevCount) => prevCount + 2);
};

//4. Object State: //TO Practice
// When dealing with state objects, you need to spread the previous state to avoid overwriting other properties.
const updateAge = () => {
// setUser((pre)=>({...pre, age: pre.age +1})) // 1 liner withot return
setUser((pre) => {
return { ...pre, age: pre.age + 1 };
});

//Syntax
setUser((p) => ({ ...p, age: p.age + 1 }));
setUser((p) => {
return { ...p, age: p.age + 1 };
});
};

// // When dealing with state objects, you need to spread the previous state to avoid overwriting other properties.
const onChangeLanguage = () => {
setLanValues({ ...lan, language: 'Marathi' }); // use {} as this is object
};

//5. Conditional Update:
// Perform a state update conditionally based on the current state or other variables.
const incrementIfEven = () => {
if (count % 2 === 0) {
setCount(count + 1);
}
};

const clickOpenTable = () => {
setOpen(!open);
};

const prevStateHandle = () => {
setOpen((prev) => !prev);
setLanValues((prev) => {
return { ...prev, isEmployed: !prev.isEmployed };
});
};

return (
<div className="App">
<button onClick={clickOpenTable}>OpenTable</button> <br />
<button onClick={prevStateHandle}>Prev_state- {lan.isEmployed}</button>
{JSON.stringify(lan)}-{open}
<br />
<br />
{open && (
<table>
<thead className={'App' + (favColor === 'red' ? 'Blue' : 'Green')}>
<tr>
<th>Id</th>
<th>Name</th>
<th>Username</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{list.map((user) => (
<tr key={user.id}>
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.username}</td>
<td>{user.email}</td>
</tr>
))}
</tbody>
</table>
)}
<button onClick={onSubmit}>Play</button>
<button onClick={onChangeColor}>Change Color</button>
<button onClick={onChangeCount2}>Change Count2 -{count}</button>
<button onClick={handleMultipleUpdates}>Change Multiple -{count}</button>
<button onClick={incrementIfEven}>Change with Condition -{count}</button>
<button onClick={onChangeLanguage}>
Change Language - {lan.language}
</button>
<button onClick={updateAge}>Object-update {JSON.stringify(user)}</button>
</div>
);
}

Q11: What are the Destructuring in ReactJS?

Assigging the array items into different variables.

Below are 2 ways

Type 1
const child = ({name, getName}) =>{ return <h1>Something went wrong.</h1>;
}
Type 2
const child = (props) =>{
const {name, age} = props
return (
<h1> {name} {age}</h1>
)}

Q12: What’s the difference between an “Element” and a “Component” in React?

Simply put, a React element describes what you want to see on the screen. Not so simply put, a React element is an object representation of some UI.

A React component is a Function or Class, which optionally accepts input and returns a React element (typically via JSX which gets transpiled to a javascript createElement invocation).

🔗 Source: medium.freecodecamp.org/

Q15: What are error boundaries in ReactJS (16)?

A JavaScript error in one part of the app shouldn’t break the entire app. Error boundary is React’s solution to this common problem. The candidate should be able to explain what an error boundary is and to use it to handle errors in your application.

In React, an error boundary is a component that catches JavaScript errors anywhere in its child component tree and logs those errors or displays a fallback UI instead of crashing the component tree. To create an error boundary, you define a class component with two lifecycle methods: componentDidCatch and render.

Here’s a simple example of an error boundary in React:

import React, { Component } from 'react';

class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}

componentDidCatch(error, errorInfo) { <<-- note1 -->>
// Log the error to an error reporting service
console.error('Error caught by error boundary:', error, errorInfo);
// You can also set a state to indicate that an error occurred
this.setState({ hasError: true });
}

render() {
if (this.state.hasError) {
// Fallback UI when an error occurs
return (
<div>
<h2>Something went wrong</h2>
<p>Please refresh the page or try again later.</p>
</div>
);
}

// Render children if no error occurred
return this.props.children;
}
}

// Example component that may throw an error
class ErrorProneComponent extends Component {
render() {
// Simulate an error
throw new Error('Error in ErrorProneComponent'); <<-- note2 -->>
// React will trigger the error boundary
}
}

// Example usage of the error boundary
function App() {
return (
<ErrorBoundary> <<-- note3 -->>
<div>
<h1>Your App</h1>
<ErrorProneComponent />
</div>
</ErrorBoundary>
);
}

export default App;

🔗 Source: github.com/sudheerj

In this example:

  • ErrorBoundary is a class component that implements the error boundary behavior.
  • componentDidCatch is a lifecycle method that gets called when an error occurs in any of its child components. It logs the error and sets the component's state to indicate that an error occurred.
  • The render method checks whether an error occurred and renders a fallback UI if needed.
  • ErrorProneComponent is an example component that may throw an error for demonstration purposes.
  • The ErrorBoundary component wraps around the potentially error-prone components (in this case, ErrorProneComponent) in the App component.

When an error occurs in the ErrorProneComponent, the error boundary (ErrorBoundary) catches the error, logs it, and displays the fallback UI instead of crashing the entire application. This helps in gracefully handling errors and providing a better user experience.

Q16: Why ReactJS uses className over class attribute?

class is a keyword in javascript and JSX in react convets into Javascript with the help to Beble, so we can’t have to same name. That’s the principal reason why React uses className instead of class.

render() {
return <span className="menu navigation-menu">Menu</span>
}

🔗 Source: github.com/sudheerj

Q18: What can you tell me about JSX?

JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to XML or HTML. It is commonly used with React to describe what the UI should look like. JSX allows you to write HTML elements and components in a syntax that resembles XML or HTML, but it is ultimately transformed into regular JavaScript by a transpiler like Babel before it is rendered in the browser.

Here's a simple example of JSX:
const element = <h1>Hello, JSX!</h1>;

Under the hood, the JSX code is transformed into
the equivalent JavaScript code using React.createElement:

const element = React.createElement('h1', null, 'Hello, JSX!');
Save to grepper
The React.createElement function is responsible for creating a virtual DOM element with the specified type, properties (or "props"), and children.

🔗 Source: codementor.io

JSX provides several advantages:

  1. Readability: JSX makes the code more readable and visually similar to HTML, making it easier for developers to understand the structure of the UI.
  2. Expressiveness: JSX allows embedding JavaScript expressions within curly braces {}. This enables dynamic content and expressions to be included directly within the markup.
const name = "John";
const element = <p>Hello, {name}!</p>;

3. Integration with JavaScript: JSX seamlessly integrates with JavaScript, allowing you to use JavaScript expressions and variables directly within the markup.

4. Consistency with HTML: Since JSX looks similar to HTML, developers familiar with HTML find it easier to work with when building React components.

Q19: Why should not we update the state directly?

If you try to update the state directly then it won’t re-render the component.

//Wrong
This.state.message =”Hello world”;

Instead use setState() method. It schedules an update to a component’s state object. When state changes, the component responds by re-rendering

//Correct
this.setState({message: ‘Hello World’});

Note: The only place you can assign the state is the constructor.

🔗 Source: https://github.com/sudheerj

Q20: What are the different phases of ReactJS component lifecycle?

There are four different phases of React component’s lifecycle:

Mounting:

There are four built-in lifecycle methods that are called in the following

  1. constructor( ) — First-Called and only runs once. We can set the initial state of the component and bind the method. ie. this.state= {}; and this.setState(name:’’rohit’’);
  2. static getDerivedStateFromProps( props, state) —Static method, helps to copy any change in props values to state. used very rarely. Called in both mounting & updating phases. Before the render method. does not have access to “this” because it has the keyword static in front of it.

What’s a static method? — don't want the user to access this keyword directly because static methods are class methods but not instance methods. Here this.setState is not called.

3. render( ) — Help to render the JSX.
4. componentDidMount( ) — It is called after render and best place to call API updates the render DOM.

Updating:

Called when re-render, any change to props/state
1. static getDerivedStateFromProps( rarely) — Static method, As above.
2. shouldComponentUpdate(props,state)(rarely) — Called when change in state or pros of the component. If there is no change we can returning ‘’false’ we can stop re-rendering. By default, it returns true. Inbuild in pure component and hence improve performance.
3. render( ) — To re-render the HTML inside the DOM, the render( ) method gets called again. Return JSX.
4. getSnapshotBeforeUpdate(rarely) — Called after render. It stores the previous state of the component so that React has an idea of what parts of the DOM needs to be updated. have old state &props. help to get “window resize, remember scroll, text position”.
5. componentDidUpdate( ) — called after the component re-rendered, just like the componentDidMount( ) method, the difference is not called on the initial render. [Any update on the event or handle the API, update the setState and componentDidMount call again. I AM DONE AND THE COMPONENT IS UPDATED.]

Unmounting:

componentWillUnmount( ) — This method is called just before the component gets destroyed. Any clean up statements should be executed inside this method.

Chat GPT :

The lifecycle of a React component refers to the various phases a component goes through, from its creation to its destruction. React components have several lifecycle methods that developers can use to perform actions at specific points in the component’s existence. As of my knowledge cutoff date in January 2022, the React lifecycle methods fall into three main categories:

Mounting Lifecycle:

  1. constructor
  • This is the first method called during the creation of a component. It is used for initializing state and binding event handlers

2. static getDerivedStateFromProps

  • This method is called right before rendering and returns an object to update the state based on the initial props. It is rarely used

3. render:

  • This is the only required method in a class component. It examines this.props and this.state and returns JSX or null or false (to render nothing)

4. componentDidMount

  • This method is called after the component has been rendered to the DOM. It is often used for initiating AJAX requests, setting up subscriptions, or performing other side effect

Updating Lifecycle:

  1. shouldComponentUpdate:
  • This method is called before rendering when new props or state are received. It allows you to prevent unnecessary re-renders by returning false under certain conditions.

2. render:

  • Re-rendering phase: Same as the mounting phase.

3. getSnapshotBeforeUpdate:

  • This method is called right before the changes from the virtual DOM are to be reflected in the DOM. It allows you to capture information from the DOM before it gets potentially changed.

4. componentDidUpdate:

  • This method is called after the component has been updated in the DOM. It is often used for handling side effects like network requests

Unmounting Lifecycle:

componentWillUnmount:

  • This method is called just before a component is unmounted and destroyed. It can be used for cleaning up resources, canceling network requests, or clearing subscriptions

Error Handling Lifecycle:

React also introduced error boundaries to catch JavaScript errors anywhere in a component tree and log those errors, display a fallback UI, or take other actions.

  1. static getDerivedStateFromError:
  • This method is called when there is an error during rendering. It allows the component to update state in response to the error.

2. componentDidCatch

  • This method is called after an error has been thrown during rendering. It is used to log the error information

Keep in mind that some lifecycle methods are considered legacy, and React introduced the concept of hooks (such as useEffect and useEffect in functional components) as an alternative to class component lifecycle methods. Depending on the version of React you are using, functional components and hooks may be a more common and recommended pattern.

7. Component life cycle

>> Mounting 
initalization
componentWillMount just before render
render
componentDidMount just after render
>> Updating
getDrivedStateFromProps invoked as soon as the props recived
componentWIllReciveProps
shouldComponetUpdate(T/F) if want update retunr true, defualt false
render
getSnapshortBeforeUpdate just after render
componetDidUpdate
>> Unmounting
componentWillUnmount clear up space
18 What is use of static in getDrivedStatefromProps? used for tuue and false. can call it directly, prevent the use of this and there is no instance and provide protection. ........................... so you cannot reference this inside. You're supposed to only look at the (latestProps, latestState) parameters, and determine what state updates if any are needed.this return new state if not change no change.18 What is use of static in getDrivedStatefromProps? used for tuue and false. can call it directly, prevent the use of this and there is no instance and provide protection. ........................... so you cannot reference this inside. You're supposed to only look at the (latestProps, latestState) parameters, and determine what state updates if any are needed.this return new state if not change no change.
26.Lifecycle Method of Reactjs - 
mounting - putting the element into DOM, constructor - set the value,
getDrivedfromState- changing the value, just before rendering,
componentdidmount, perform side effect, fetch api
Updating - check medium
Unmoving26.Lifecycle Method of Reactjs -
mounting - putting the element into DOM, constructor - set the value,
getDrivedfromState- changing the value, just before rendering,
componentdidmount, perform side effect, fetch api
Updating - check medium
Unmoving

What are the different lifecycle methods?

  • componentWillMount (deprecated) - this is most commonly used for App configuration in your root component.
  • componentDidMount - here you want to do all the setup you couldn’t do without a DOM, and start getting all the data you need. Also if you want to set up eventListeners etc. this lifecycle hook is a good place to do that.
  • componentWillReceiveProps (deprecated) - this lifecyclye acts on particular prop changes to trigger state transitions.
  • shouldComponentUpdate - if you’re worried about wasted renders shouldComponentUpdate is a great place to improve performance as it allows you to prevent a rerender if component receives new prop. shouldComponentUpdate should always return a boolean and based on what this is will determine if the component is rerendered or not.
  • componentWillUpdate (deprecated) - rarely used. It can be used instead of componentWillReceiveProps on a component that also has shouldComponentUpdate (but no access to previous props).
  • componentDidUpdate - also commonly used to update the DOM in response to prop or state changes.
  • componentWillUnmount - enables you can cancel any outgoing network requests, or remove all event listeners associated with the component.

Mount (initial render) -> updates (re-render) -> unmount

//1. Mount (initial render) — component is added to screen, like click on show button will add the component.
//2. updates (re-render) — when state or props changes. this change the value
//3. unmount

useEffect(()=>{
//after every render[RUN ALL THE TIME] at 1 & 2 not at unmounting
})
useEffect(()=>{
//after every render[RUN ONLY 1 TIME], RUN AT UNOUNT,
// CLEAN UP
return () => console.log('unmount')
},[])
useEffect(()=>{
//after every render[RUN WHEN VALUE CHANGE IN COUNT]
},[count])
function App() {
const [isShown, setIsShown] = useState(true);
  return (
<>
<button onClick={() => setIsShown(!isShown)}>
{isShown ? 'Hide Counter' : 'Show Counter'}
</button>
{isShown ? <Counter /> : null}
</>
);
}
function Counter() {
const [count, setCount] = useState(0);
const [bool, setBool] = useState(false);
return (
<>
<button onClick={() => setBool(!bool)}>Re-Render</button>
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>Count: {count}</p>
</>
);
}

Problme useeffect, Infinity loop

useEffect(()=>{
setCount(count +1)
},[count])
fix:
useEffect(()=>{
if (count === 20) return
setCount(count +1)
},[count])

Q.21 Prevent components from re-rendering?

Below is the way to prevent re-rendering.
1. ShouldComponentUpdate

2. React.PureComponent — don’t use shouldComponentUpdate, as it does the shallow compare. and both are the same.

3. React.memo — use tech of memorization and if we render same this it should not re-render. Functions are stored in the memory.

4. useCallback — help to stop rerendering the child component, as components are passed as props

Q.22. Events in React?

Wrapper around the actual DOM event, why wrapper? It helps to handle different browser (ie, chrome). How the event works on list <li onClick={}/>, basically it don't handle at the element level but much higher level

function clickHandle(e){}<div onClick={clickHandle} />

React FORM

****READT FORM ****

DEFAULT HTML FORM BEHAVIOUR IS ON SUBMIT IT WILL TAKE
TO NEXT PAGE. IN REACT IT WILL BE ON THE SAME PAGE AND THEN WE CAN SEND
DATA OR DO VALIDATION i.e <form onSubmit=[formSubmit]>

Problem : below value="rohit" is treated as Props, which is read only so we
cannot change the value
"you provided the"value" filed for form with out onchange property"

FIX: defaultValue="John" you can edit it.


****CONTROLED COMPONENT****

TO FIX, WE NEED TO CHANGE THE VALUE WITH ONCHANGE OR USESTATE, SO THIS IS
CONTROLED COMPONET AS REACT IS CONTROLLING TO DO THE FIX

export default function FORMEX() {

const [name, setName] = useState()
// const name = "rohit"

const handleChange = (e) =>{
console.log(e.target.value);
setName(e.target.value);
}
return (
<div>
<form onSubmit={e=>{
e.preventDefault();
dispatch({type:"add-todo", text});
settext("");
}}>
<h1>CONTROLED COMPONENT</h1>
<input type="text" value="rohit" /> // ERROR:cant edit
<input type="text" value={name} /> // error still cant edit it
<input type="text" value={name}
onChange={(e)=> setName(e.target.value)} /> //fix, can change now
<input type="text" value={name}
onChange={handleChange} /> //fix, can change now//fix, can change now
</form>
</div>
)

Q24: What is the difference between a controlled component and an uncontrolled component?

  • A controlled component (better) is a component where React is in control and is the single source of truth for the form data by using the setState, This is bound to the setState component.

CONTROLLED (useState with onChange)

****************Controled componet with single handler

export default function ControledForm() {

const [name, setName] = useState()
const [pwd, setPwd] = useState()

const handleChange = (e) =>{
if(e.target.name==="userid){
setName(e.target.value);
}else{
setPwd(e.target.value);
}
}

const handleSubmit = () =>{
console.log("the name and passsword is", name, pwd)
}
return (
<div>
<form onSubmit={handleSubmit}>
<h1>CONTROLLED component</h1>
<input type="text" name="userid" value={name} onChange={handleChange} />
<input type="text" name="password" value={name} onChange={handleChange} />
</form>
</div>
)

UNCONTROLLED COMPONENT (useRef)

useRef - this is uncontroled component, bacause react have no control and 
DOM can be manuplated directyly. React recommends to use controled Component.

import React, { useRef } from 'react';
const UseReference = () => {
const username = useRef(null);

const handleBtnClick = () => {
username.current.value = "The is the story of your life.";
username.current.focus();
};
return (
<div>
<input type="text" ref={username} />
</div>
);
};
export default UseReference;

What can you do with HOC?

Higher-order components (HOC) is a pattern derived from React’s compositional nature. The interviewer might ask this question to better understand the candidate’s familiarity with React’s component system. As the candidate, you should be able to explain what HOCs are conceptually and also what problem it solves.HOC is a function that accepts a component and returns a new component. These components are also referred to as pure components as they accept dynamic child component but doesn’t modify or copy any of the child components.Suppose we have componet and need to use reuse this at many place 
we can use the HOC.
Use cases of HOCs include:
1. Code reuse and logic abstraction
2. State abstraction and manipulation
3. Props manipulation
4. Render hijacking
// difine simple componet
const MyComp = (props) => {
return <div>{props.message}</div>;
};

//create higher order compont
const AddNewHOC = (WrapperComponet) => {
return (prop) => {
return <MyComp message={`My Fist HOC : ${prop.message}`} />;
};
};

//yse the HOC to enhance the original component
const EnhancedComponent = AddNewHOC(MyComp);


const App = () =>{
return (
<EnhancedComponent message="Hello, World!" />
)
}

output

My Fist HOC : Hello, World!

HOC(Higher Order Function)
>>> Hoc is the fuction that takes the another function as parameters
or returs a function. **important or **

EX. —

  1. setTimeout
  2. closuer
  3. map
  4. reducer
  5. filter
  6. sort

Why it do it?? WHy a funcation take any parameter?
>>> It takes parameter to perform some action.

function twice(f, v) {
return f(f(v))
}

function add3(v) {
return v + 3
}
const result = twice(add3, 1)
console.log("Result is ", result) //7
// -------------------------------
function double(n){
return n*2
}
double(10) //100, what if simple value/n is not enough
>>> Higher-order components
A HOC takes a component as input parameter and returns a new component.

Let's look at an example of the most simple HOC possible.
const HelloComp = ({ name }) => <h1>Hello {name}!</h1>;

// Take in a component as argument WrappedComponent
function simpleHOC(WrappedComponent) {
// And return a new anonymous component
return class extends React.Component{
render() {
return <WrappedComponent {...this.props}/>;
}
}
}
const NewComponent = simpleHOC(HelloComp);
const App = () =>
<div>
<NewComponent name="CodeSandbox" />
</div>;

Closure

setTimeout/clouser function — both returns the function

>>> setTimeout // callback function // do some thing, this require function, 
//and wait for some time to do the operaion

setTimeout(()=>{})

// or
setTimeout(function(){})

// or
setTimeout(fn);

const fn = function(){
// do some thing code
}
const fn = () =>{}

Clousure

>>> clouser function
function makeHadler(size){
return function(){
returns size * 100
}
}
const fit = makeHadler(20) // 2000
const fit = makeHadler(10) // 100 //reusing & removing duplicaion
const fit = makeHadler(5) // 500 //reusing & removing duplicaion

Map/Filter/Sort/Reduce


arrayNames.filter(function(n){
if(n[0]==='Q')
return false
return true
})


const originalArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];

const result = originalArray
.filter((value) => value % 2 === 0) // Keep only even numbers
.map((value) => value * 2) // Double each remaining number
.sort((a, b) => a - b) // Sort the numbers in ascending order
.reduce((acc, currentValue) => acc + currentValue, 0); // Sum all the numbers

console.log(result); // Output: 40

Why above is usefull?, we can do it with for loop
>>> because we are removing duplicating the logic
// filtering is very common thin to do and there is patter

---
var originalArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];

var returnArr = originalArray

.filter((s) => s > 4)
.sort((a,b)=>a-b)
.map((item) => {
return item
//return item > 1;
})
.reduce((acc,curr)=> {
return (acc+curr)
},0);
console.log(returnArr);

What are pure components?

A pure function is a function that doesn't depend on and doesn't modify the states of variables out of its scope. Essentially, this means that a pure function will always return the same result given same parameters.

🔗 Source: github.com/Pau1fitz

Q25: What does mean in React Side Effect? Provide some examples.

Side effects are basically anything that affects something outside of the scope of the current function that’s being executed. In our dashboard, this includes:

  • API requests to our backend service
  • Calls to our authentication service
  • Error tracking calls

Pure functions are deterministic (meaning that, given an input, they always return the same output), but that doesn’t mean that all impure functions have side effects. Generating a random value within a function makes it impure, but isn’t a side effect, for example. React is all about pure functions, and asks that you keep several lifecycle methods pure.

🔗 Source: reddit.com

Q 26. Conditional Rendering

if (isLair){
return <Animation />
retunr <NoAnimation />
-----------------------------------//here there is no falsy, if isLiar is fale then valeu will be empty/null
{ isLiar && <Animation /> }
-----------------------------------
{ idLiar ?
<Animation />
): (
<NoAnimation />
)}
Using switch statement for multiple conditions:
function ConditionalComponent({ option }) {
switch (option) {
case 'A':
return <p>Option A is selected.</p>;
case 'B':
return <p>Option B is selected.</p>;
default:
return <p>No option selected.</p>;
}
}
Conditional rendering with logical OR (||):
function ConditionalComponent({ value }) {
return (
<div>
{value === 'X' && <p>Render when value is X</p>}
{value !== 'X' && <p>Render when value is not X</p>}
</div>
);
}

Q27: Difference between React and Angular.js

React is library and angular is framework.

React is one way binding and Angular is two way binding.

Angular component create 4 files in which it hold the html and css concept.

Angular is on Typescript, and React can be written in both.

React build on 3rd party library.

React work on the Virtual DOM and Angular work on the real DOM.

React debugging is compile time, Angular is run time.

React author Facebook, Angular author Google.

Q.28 What is the difference between the functional component and class component?

A functional component is used when you are not going to use any state. It’s basically stateless. Whereas, a class component is used when you need state in your component

Q 29. Is setState( ) asynchronous? How can you explain it’s behaviour?

setState( ) actions are asynchronous. setState( ) does not mutate this.state immediately. Instead, it makes a pending state transition. Accessing this.state just after calling setState( ) may return the existing value.Question: Asynchronous behavior of setState( ) results in a performance gain. How? 
Ans: setState( ) update the state and cause rendering. This may result in an expensive action if made synchronous and may cause the browser to stay unresponsive. Hence, setState( ) is made asynchronous which increase the performance.

Q. 30. What is the purpose of the callback function as an argument in setState()?

In React, the setState function is asynchronous, and it may take a callback function as a second argument. This callback is executed after the state has been updated and the component has been re-rendered. The callback function is often used to perform actions that depend on the updated state.

Here’s an example of using a callback function with setState:

import React, { useState } from 'react';

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

const handleClick = () => {
// Using setState with a callback
setCount((prevCount) => prevCount + 1, () => {
// Callback function executed after state is updated
console.log('State updated! New count:', count);
});
};

return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
};

export default MyComponent;

Summary :
In this example, when the button is clicked, the handleClick function
is called. Inside handleClick, setCount is used with a callback function.
The callback function receives the previous state (prevCount) and
performs the state update based on the previous state. Additionally,
it contains a callback that is executed after the state has been updated.

It's important to note that the count value inside the callback will not
be the updated value immediately after calling setCount. React batches
state updates for performance reasons, and the updated value is not
guaranteed to be available synchronously. If you need to perform an
action after the state has been updated, the callback function is the
appropriate place to do so.
Since setState( ) is asynchronous, if we want to perform any action which needs to be executed after the completion of setState( ), we use a callback.

Q. 31. What are the keys and refs in ReactJS?

each list should have a key element. Key help to identify which elements have been added updated or deleted. Key gives the element a stable identity.

https://www.youtube.com/watch?v=bgmiKEPx2pY&list=PLp18NAIKHWnvpLpioGs6ZAiMlpfx49KOz&index=20

function MapList() {
const list = ['red', 'blue', 'green'];

return (
<div className="App">
{list.map((item,index) => {
return <h2 key={index}>{item}</h2>; //fix key issue with key={index}
})}
</div>
);
}
Keys in react are used to uniquely identify value, help to change specific virtual DOM elements which is been updated/delete or change.Increase performance as only the changed component are re-rendered.
<li key={name}> {name}</li>
Keys need to be unique among their siblings. They don’t need to be unique globally. For example, the same set of keys can be used for 2 different arrays. Ex. suppose we have used the key, and the value of the elements deleted in react then react-dom will shift up hence we will not be able to figure which item was deleted actually.
Refs are shorthand for references. It is an attribute that helps to store a reference for a particular react element or a component. Usually, props are transferred from the parent component to child component.However, sometimes you might need to change the child without re-rendering it with new props. That’s where ref attribute come into existence. When passing a ref attribute to an html element, we pass that very DOM element as an argument to the callback function.

Example 1: Using key for Dynamic Lists

When rendering a dynamic list of components in React, it’s important to assign a unique key prop to each item. This helps React efficiently update and re-render the list when the underlying data changes.

import React from 'react';

const DynamicList = ({ items }) => {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};

const App = () => {
const data = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
];

return <DynamicList items={data} />;
};

export default App;

Summary:
In this example, each <li> element has a unique key based on the id
property of the data items. This ensures React can efficiently update
the list when items are added, removed, or reordered.

Example 2: Using ref to Access a DOM Element or a Component

The ref attribute allows you to get a reference to a React element or component. This can be useful for accessing and interacting with the DOM directly or getting information from a child component.

import React, { useRef, useEffect } from 'react';

const TextInput = () => {
const inputRef = useRef(null);

useEffect(() => {
// Focus on the input element when the component mounts
inputRef.current.focus();
}, []);

return <input type="text" ref={inputRef} />;
};

const App = () => {
return (
<div>
<h1>Using Ref in React</h1>
<TextInput />
</div>
);
};

export default App;

Summary:
In this example, the useRef hook is used to create a reference (inputRef)
to the input element. The useEffect hook is then used to focus on the
input element when the component mounts.

These are basic examples, and the use of key and ref can become more
complex depending on your specific requirements. However, these examples
should give you a good starting point for understanding their usage
in React.

Q 32. What are pure components in ReactJS?

React.PureComponent is exactly the same as React.Component except that it handles shouldComponentUpdate( ). Whenever any state or props change, pure components make a shallow comparison between the previous state/props and the new one. Whereas the Component does not make any comparison to the next out the box. Thus, the component re-renders by default whenever shouldComponentUpdate( ) is called.

In React, a Pure Component is a type of component that extends the React.PureComponent class rather than the more commonly used React.Component class. The main feature of Pure Components is that they automatically implement a shouldComponentUpdate method with a shallow prop and state comparison. This means that a Pure Component will only re-render if its props or state have changed, preventing unnecessary renders and potentially improving performance.

import React, { PureComponent } from 'react';

class MyPureComponent extends PureComponent {
render() {
return <div>{this.props.message}</div>;
}
}

export default MyPureComponent;

Summary:
In this example, MyPureComponent extends PureComponent, and it will only re-render if there are changes in its props or state.

Q 33. Explain the significance of the Arrow function in ReactJS? (IMP)

Arrow function, something looks like this ‘=>’ is a short-hand notation for writing function. These functions allow binding the context of the component properly since ES6 doesn’t allow auto-binding by default. Returns another function.

state = {
loggedId: false
}

loginHandler=()=>{
this.setState(prevState =>({
loggedIn: ! prevState.loogedIn
}))
}

https://www.youtube.com/watch?v=uRkS5Dqf8ic&list=PL7pEw9n3GkoUZqnNQEVbLfTTVBIWBxXg9&index=1 (8.4min)

React has onClick handler, which is not a class method, but a class property. Above picture render() is a class method but loginHandle is class property, generally we defined this loginHandle inside the class and with this…. ()=>{}, define as function then we have a function inside a function, then the ‘’this’’ will belong to function but not class, For making this belongs to the class we can 2 things as below:

In React, when you use an arrow function as an event handler or within a callback, the this keyword behaves differently compared to regular functions. In an arrow function, this retains the value of this from the enclosing lexical scope, meaning it does not have its own this context.

Here’s a brief explanation:

Arrow Function:

class MyComponent extends React.Component {
handleClick = () => {
console.log(this);
};

render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}


In this example, handleClick is an arrow function. When the button is
clicked, this inside handleClick refers to the instance of MyComponent.
This behavior is different from using a regular function:

Regular Function:

class MyComponent extends React.Component {
handleClick() {
console.log(this);
}

render() {
return <button onClick={this.handleClick.bind(this)}>Click me</button>;
}
}

In this example, handleClick is a regular function. To ensure that this inside handleClick refers to the instance of MyComponent, we use ‘.bind(this)’ when attaching the event handler.

Arrow Functions and this:
Arrow functions: Automatically bind ‘this’ to the value of th’is in the enclosing lexical scope (in this case, the component instance).

Regular functions: Do not automatically bind ‘this’, and you may need to use methods like‘ .bind(this)’ or explicitly ‘bind this’ in the constructor ‘(this.handleClick = this.handleClick.bind(this))’.

Using arrow functions for event handlers in React components is a common practice because it helps avoid issues with this binding. However, it’s essential to be aware of the potential differences in behavior, especially when comparing arrow functions to regular functions in certain contexts.

34. Improve React.js Performace

1. Use the Production Build - npm run build
2. useMomo()
3. virtualized long list - only show the list visible to window called 'windowing'. Use react-window and react-virtualized npm pakage.
4. Web pack and dev-tools.
5. React.PureComponent
6. memoize- Cashing function -
cont memexpensivecom = memoize(expFunction)

8. Web Worker - JS run on the single thread for long running process we can add new thread to the process request. This is done by the web worker. Officially not supported.
9. lazy loading
10. React.memo() - memorise value and only render if the value change. Same achived by shouldComponetUpdate and pureComponent class.
11. useCallback() -
12. ShouldComponentupdate() return false, default is true

Thanks 🙌 for reading and good luck on your interview!
Please share this article with your fellow devs if you like it!
Check more FullStack Interview Questions & Answers on 👉 www.fullstack.cafe

  • ***************************************************************

Form Example

import React, { Component } from 'react'//https://www.youtube.com/watch?v=DLX62G4lc44&list=PLWKjhJtqVAbkArDMazoARtNz1aMwNWmvC&index=2&t=124sexport default class UserForm extends Component {
constructor(){
super()
this.state = {
firstName: "" ,
lastName: "",
age:0,
gender:"",
favColor:"green",
dietaryRestriction: {
isVagan:false,
isKosket:false,
isLactoseFree:false
}
}
}
//for firstName and last Name
// handleChange = (event) => {
// const {name, value} = event.target
// console.log(name, value)
// this.setState({ [name]: value })
// }

//for firstName and last Name and checkbox
handleChange = (event) => {
const {name, value, type, checked} = event.target
// type==="checkbox" ?
// this.setState({ [name]:checked })
// : this.setState({ [name]:value })

type==="checkbox" ?
this.setState(prevState => {
return{
dietaryRestriction:{
...prevState.dietaryRestriction,
[name]:checked }
}
}
)
: this.setState({ [name]:value })
console.log(name, value)
}
formSubmit = (event)=>{
event.preventDefault()
console.log(this.state)
}
render() {
return (
<form onSubmit={this.formSubmit}>
<dir>
<h3>User Registration Form</h3>
<input type="text" value={this.state.firstName} name="firstName" placeholder="First Name" onChange={this.handleChange} /><br/>
<input type="text" value={this.state.lastName} name="lastName" placeholder="Last Name" onChange={this.handleChange} /><br/>
<input type="text" value={this.state.age} name="age" placeholder="age" onChange={this.handleChange} /><br/>
<textarea value={"Some default value"} onChange={this.handleChange} /><br/>
<label>
<input type="checkbox" name="isFriendly" value="isFriendly" checked={this.state.isFriendly} onChange={this.handleChange}/> Is Friendly
</label><br/>
<label>
<h5>Customer Diet</h5>
<input type="checkbox" name="isLactoseFree" checked={this.state.dietaryRestriction.isLactoseFree} onChange={this.handleChange}/> isLactose Free? <br/>
<input type="checkbox" name="isVagan" checked={this.state.dietaryRestriction.isVagan} onChange={this.handleChange}/> isVagan Free?<br/>
<input type="checkbox" name="isKosket" checked={this.state.dietaryRestriction.isKosket} onChange={this.handleChange}/> isKosket Free?<br/>
</label><br/>


<label>
<input type="radio" name="gender" value="male" checked={this.state.gender==="male"} onChange={this.handleChange}/> Male
</label>
<label>
<input type="radio" name="gender" value="female" checked={this.state.gender==="female"} onChange={this.handleChange}/> Female
</label> <br />


<label>Favorate Color:</label>
<select value={this.state.favColor} name="favColor" onChange={this.handleChange}>
<option value="">--Please Select---</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
{/* <h5>{this.state.firstName} and {this.state.lastName}</h5> */}
{/* <h5>You are {this.state.isFriendly} and {this.state.gender} */}
<h5>{JSON.stringify(this.state)} </h5>
<button >Login</button>
</dir>
</form>
)
}
}

Q1. Important Question React

1. What is React-DOM
2. How react-Dom and virtual Dom and why its fast.
3. What is JSX and why it is used any why its fast. -it directly community with JS with out using any createReact function
4. How react-Dom and virtual Dom and why its fast?
5. What is Flux?
6. What are the advantages of ReactJS?
7. What are the major features of ReactJS?
8. What is the difference between a Presentational component and a Container component?
9. What is the difference between state and props?
10. What are the limitations of ReactJS?
11. What’s the difference between an “Element” and a “Component” in React?

13. Why ReactJS uses className over class attribute?
15. What can you tell me about JSX?
16. Why should not we update the state directly?
17. What are the different phases of ReactJS component lifecycle?

21. Difference between React and Angular.js
Q22: What is Beble and Webpack?
Web pack - This help to Bundle the task.
Beble - Help to convert JSX into Javascript.
setState ->If you try to update state directly then it won't re-render the component.Q19: What is React Dev Tool-
help to see the html, component flow and network call.
23. module -
export default com

import {com} from '../com'.
Note: when we use default we have to use the {} in import

PENDING/TO DO QUESTION

What is function composition? Write sample code for HOC and pass some dummy state/props from it.What is the purpose of super (props)?
....CSS
* CSS from https://codepen.io/cliftwalker/pen/XJaEXY */
@import url(https://fonts.googleapis.com/css?family=Open+Sans:400italic);
blockquote{
font-size: 1.4em;
width:60%;
margin:50px auto;
font-family:Open Sans;
font-style:italic;
color: #555555;
padding:1.2em 30px 1.2em 75px;
border-left:8px solid #78C0A8 ;
line-height:1.6;
position: relative;
background:#EDEDED;
}

Q7. What is a hook?

React Hooks are functions that enable functional components in React to have state and lifecycle features. Before the introduction of hooks in React 16.8, stateful logic and lifecycle methods were only available in class components. With hooks, functional components can now manage state and side effects, allowing for more concise and readable code.

Basically, it allows to hooks into the react life cycle within the functional component. Also help to share logic like HOC(wrapper hooks), render props with the help of custom hooks. ex useState(‘name’), useEffect(‘…’), useMemo().

Prior to Hooks, React was using the class component to persist the data(State) inside it was having class, methods(lifecycle), and states. But to make functional components do the same as class components Hooks came. This is done through the closure.

useEffect Hooks


>>>>Side Effect
Event : Add. /remove event litner
Observer Pattern : Subscribe /unSubscribe
Closure
Timers : setInterval, setTimeout, clearInterval, clearTimeout
useState
Mounted / unmounted
----

>>>>Call API

1. Update API
- Title update
2. Call API
3. Listen DOM events
a) scroll
b) Resize
4. Cleanup
- Remove listner / usnSubscribers
- Clear timer

useEffect(callback, [deps])

1. useEffect(callback) //mounted, all time, change in setState
2. useEffect(callback, []) //1 time called
3. useEffect(callback, [deps]) //called only when the value of deps changes

Ex:
document.title = "HOC"


#Why Hooks?

A different way of doing the same things.

No more complex lifecycle methods.

Redux- Simple code. No more mapStateToProps, mapDispachToProps with redux

#Rules of Hooks?

Only call from the top level

Don’t call hooks inside the loops, conditions, or nested funcations.

Call hooks from React Funtion Components

Error Boundary-> both these are not available and we can do with the custom hooks

getDerivedStateFromError()  componetDidCatch()
  1. What are react hooks?
    2.Rules to apply apply hooks?
    3.Hook used to implement life cycle?
    4.Syntax of useState hooks?
    5.useReducer vs useContenxt Hooks?
    6.Hooks use for oprimisation?
    7.What are custome hooks and when to use them?
    8.Share state between component utilizaing the same hooks
    9.How to use useEffect to call the loading func just onece?
    10.useState vs useRef?

3. Hooks Lifecycle?

React hooks don’t have a lifecycle in the traditional sense like class components do. However, they have a lifecycle of their own, known as the “hook execution order” or “rules of hooks.” Understanding the sequence of hook execution is crucial for writing effective and bug-free functional components.

Here’s the typical sequence of hook execution:

  1. useState and useReducer: These hooks are called during every render. They allow you to manage state in functional components.
  2. useEffect, useLayoutEffect, useRef:These hooks are called after the render is committed to the screen. useEffect is commonly used for side effects like data fetching, subscriptions, or manually changing the DOM.
  3. useContext:useContext is called after useEffect. It allows you to subscribe to React context within a functional componen
  4. Custom Hooks: If your component uses any custom hooks, they will be called in the order in which they are invoked.
    It’s important to note that the sequence of hook calls is consistent across renders. Hooks must be called in the same order in every render to maintain proper state and function. Also, hooks cannot be conditionally called or called inside loops.

Here’s a simple example to illustrate the hook execution order:

import React, { useState, useEffect } from 'react';

function MyComponent() {
// 1. useState
const [count, setCount] = useState(0);

// 2. useEffect
useEffect(() => {
// This effect will run after the render is committed to the screen
console.log('Effect ran!');
}, [count]); // Dependency array ensures the effect only runs when
//count changes

// 3. Render
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

export default MyComponent;
//n this example, useState is called first to manage the component's
//state, then useEffect is called after the render to handle side effects

useReducer vs useContext Hook


useReducer and useContext are two distinct React hooks that serve
different purposes, but they can be used together in certain scenarios.
Let's explore each hook and discuss when to use them:

---->useReducer
Purpose: useReducer is primarily used for managing complex state logic
in a more organized way, especially when the state transitions are
not straightforward and involve multiple sub-values or when the next
state depends on the previous state.

---->useContext:

Purpose: useContext is used to subscribe to a React context within a
functional component. It allows components to access values stored in a
context without manually passing them down through props.

Example:

---->Using useReducer with useContext:

In some cases, you might use both useReducer and useContext together.
For example, if you have a complex state that needs to be shared across
multiple components, and you also want to update that state based on
actions, you could use useReducer to manage the state transitions and
useContext to share the state with other components.

import React, { createContext, useContext, useReducer } from 'react';

const MyContext = createContext();

const initialState = { count: 0 };

function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
throw new Error();
}
}

function MyProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);

return (
<MyContext.Provider value={{ state, dispatch }}>
{children}
</MyContext.Provider>
);
}

// In another component
function MyComponent() {
const { state, dispatch } = useContext(MyContext);

return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>
Increment
</button>
</div>
);
}

In summary, while useReducer is focused on managing state transitions,
useContext is used for subscribing to context values. They can be used
together when you need to manage complex state logic shared among multiple
components.

7. What are complex hooks and when to use it?

Custom hooks are reusable functions in React that encapsulate logic and can be shared across components. These hooks allow you to extract and reuse stateful logic from components, promoting code reusability and maintaining a clean and modular codebase. Custom hooks follow the naming convention of starting with “use” to signal that they may use React hooks internally.
1. Reusability:
2. Complex State Logic:
3. Abstraction of Concerns:
4. Improving Testability:
5. Maintainability
6. Sharing Logic:

8. Share state between component utilizaing the same hooks

If you want to share state between components using the same hook, you can create a custom hook and use it in both components. This allows you to encapsulate the state logic and share it seamlessly. Here’s an example using the useState hook:

import React, { useState } from 'react';

// Custom hook for managing shared state logic
function useSharedState(initialValue) {
const [sharedState, setSharedState] = useState(initialValue);

const updateSharedState = (newValue) => {
setSharedState(newValue);
};

return [sharedState, updateSharedState];
}

// Component A
function ComponentA() {
const [sharedState, updateSharedState] = useSharedState('Initial Value');

return (
<div>
<h2>Component A</h2>
<p>Shared State: {sharedState}</p>
<button onClick={() => updateSharedState('Updated Value in A')}>
Update State in A
</button>
</div>
);
}

// Component B
function ComponentB() {
const [sharedState, updateSharedState] = useSharedState('Initial Value');

return (
<div>
<h2>Component B</h2>
<p>Shared State: {sharedState}</p>
<button onClick={() => updateSharedState('Updated Value in B')}>
Update State in B
</button>
</div>
);
}

// App component
function App() {
return (
<div>
<ComponentA />
<ComponentB />
</div>
);
}
export default App;

In this example, useSharedState is a custom hook that uses the useState
hook internally. Both ComponentA and ComponentB use this custom hook
to access and update the shared state. When the state is updated in
one component, the change is reflected in the other component as well.

This pattern allows you to create reusable state logic and share it across
multiple components, promoting a clean and modular design.

9.How to use useEffect to call the loading func just once?

1. useEffect(callback) //mounted, all time, change in setState
2. useEffect(callback, []) //1 time called
3. useEffect(callback, [deps]) //called only when the value of deps changes

10. useState and useEffect

useState
useState is used for managing state in functional components. It allows
you to declare state variables and provides a function to update them,
triggering a re-render of the component.
Note: Changes to state variables trigger a re-render of the component,
and the updated state is available in the next render.

useRef
useRef is primarily used for persisting values across renders without
triggering re-renders. It is commonly used to create mutable objects that
persist for the entire lifecycle of the component.

Key Differences:

Re-renders:

useState triggers a re-render when the state is updated.
useRef does not trigger re-renders when its value changes.
Rendering Impact:

Changes to useState variables will cause the component to re-render.
Changes to useRef do not affect the rendering of the component.
Persistence:

useState variables are local to the component and reset on each render.
useRef values persist across renders and are not reset.
Access to Current Value:

To access the current value of a useState variable, you directly use the variable.
To access the current value of a useRef object, you use the current property (ref.current).

Q8. UpGrade Class project to Hooks Projects

1. Upgrade react and react-dom version ->Test (automation or manul)

2. Upgrade code 1 class route at a time -> Test

3. this.state -> useState

4. lifecycle Events → useEffect →Test

5. note — just menthon that to convert redux and routing.

Q9. How to Debug react hooks

1. Good old insprector

2. console.log, Debugger statements

3. React Developer Tools(chrome plugin)

4. useDebugValue (new)

Q10. Best way to use the hooks

  1. follow the hooks rule
  2. use linter and follow linter in the project setup
  3. const [a, setA] = useState() ;

const [b, setB] = useState();

call setA(); and setB(); in same function, have some common variable

  1. useEffect(()=>{x=somehting},[])
  2. Strategy to update react. — week dedicate for the new version after 6 to 9 months

Q11. #Basic Hooks

Came into 16.8 version and used to manage the state. How to compare and manage state

a) useState,

this is a hook that allows you to use state inside of function component

UPDATE USESTATE:

At 1 and 2, First, Make the copy with spread Operation and update the value
setValues({…values, last name:"Raj"})

USESTATE WITH ARRAY

function UseStateArray() {
const [values, setValues] = React.useState({
language: "",
yearsExperience: 0,
isEmployed: false,
});

function handleClick(event) {
setValues({...values, language:"HINDI"}) //1
setValues((prevState) => { //2
return { ...prevState, isEmployed: !prevState.isEmployed };
// It is essential to return the new state from this function
});
}

return (
<button onClick={handleClick}>Change State</button>
);
}

b) useEffect,

useEffect lets us perform side effects in function components. What are side effects?

Side effects are where we need to reach into the outside world. For example, fetching data from an API or working with the DOM

Side effects are actions that can change our component state in an unpredictable fashion (that have cause ‘side effects’)

It performs the same task as life cycle methods componentDidMount, componentDidUpdate, and componentWillUnmount.

1) componentDidMount - useEffect(()=>{ }, [])
2) componentDidUpdate - useEffect(()=>{ }, [count])
3) componentWillUnmount- useEffect(()=>{ clean up and return abc}, [count])

useEffect(()=>{
return()=>{
//cleanup
}
},[pro1,pro2])

c. useContext,

accepts a context object (the value returned from React.createContext ->Provider -> Consumer) and returns the current context value, as given by the nearest context provider for the given context. When the provider updates, this Hook will trigger a rerender with the latest context value.


//step 1
// --> Root Funcation App.js
// const UserContext = React.createContext()//1
// const MyProvider = UserContext.Provider; //2
// --> <MyProvider value={username}> //3
Step 2
// ---> Child function HeaderDetails.js
// --> const usename = useContext(UserContext)//4
// --> retunr {usename.name}//5
APP.JS>USECONTEXT>HEADER>HEADERDETIALS.JS
import React, { useState, useContext, useReducer } from 'react';

const UserContext = React.createContext() //1
const MyProvider = UserContext.Provider; //2

function Header({city}) {
return <HeaderDetails mycity={city}/>;
}

function HeaderDetails(city) {
//or <UserContext.Consumer>...//3
const usename = useContext(UserContext)

return <h1>{city.mycity} & name is {usename.name}</h1>; //4
}

return (

<MyProvider value={username}>
<Header city={'London'} />
</MyProvider>

----------------ONE PAGER useRecuer-----------
https://www.youtube.com/watch?v=wXLf18DsV-I&list=PLPxbbTqCLbGE5AihOSExAa4wUM-P42EIJ&index=2

import React, { useReducer } from "react";

export default function Form() {
const [fname, setName] = React.useState();
const [state, dispatch] = useReducer(
(state, action) => {
switch (action.type) {
case "ADD":
console.log("ADD", state, action);
return {
...state,
count: (action.payload += 10)
};
case "CHANGENAME":
console.log("CHANGENAME", state, action);
return {
...state,
name: action.payload
};
default:
return state;
}
},
{
count: 3,
name: ""
}
);

return (
<>
<input
type="text"
name={fname}
onChange={(e) => setName(e.target.value)}
/>
<button
onClick={() => {
dispatch({ type: "ADD", payload: 20 });
}}
>
Add Count
</button>
<button
onClick={() => {
dispatch({ type: "CHANGENAME", payload: fname });
}}
>
Add Name
</button>
<h1>{state.count}</h1>
<h1>{state.name}</h1>
</>
);
}
-------------------------useReducer------------------------------

//Reducer -
A reducer accepts a state and an action as an argument and returns a
new state as a result. Here's a common example of a reducer

//useReducer : The useReducer hook is very similar to the useState hook,
it allows you to manage a state and rerender the component
whenever your state changes, It accepts a reducer and
an initial state (like the example above) and returns a
new version of the state and a dispatch method
based on the action performed in the reducer

import React, { useState, useContext, useReducer } from 'react';

const initialState = { num: 0, username: "Mickel", isAuth: false };
function reducer(state, action) {
switch (action.type) {
case "increment":
return { num: state.num + 1 }; //3
case "decrement":
return { num: state.num - 1 };
case "LOGIN":
return { username: action.payload.username, isAuth: true };
default:
throw new Error();
}
}

const [state, dispatch] = useReducer(reducer, initialState); //1
// The updated retured state from reducer funcatino will come and
update above state.

return (
<div>Num: {state.num}</div> //4
<div className="grid">
<button onClick={()=>dispatch({type:"increment"})}>+</button> //2
{state.num ? (
<button onClick={()=>dispatch({type:"decrement" })}>-</button> ):
(<div />
)}
Current user: {state.username}, isAuthenticated: {state.isAuth}
<button onClick={handleLogin}>Login</button>
</div>
</div>
)

useReducer with dispatch to child

// pasing dispatch in child
import React, { useState, useReducer } from 'react';
import produce from 'immer';

// useReducer with deep down dispatch passing in child,
// and showing value on parent.

export default function UseRedcuerWithDisptact() {
const [state, dispatch] = useReducer(
(state, action) => {
console.log('action', state, action);
switch (action.type) {
case 'ADD':
return { ...state, count: state.count + Math.random() };
case 'SUB':
return { count: state.count - 1 };
case 'EMAIL_CHANGE':
// return { ...state, email: action.payload };
return produce(state, (draft) => {
draft.email = action.payload;
});
default:
return state;
}
},
{
count: 0,
email: '',
}
);
console.log('state', state);
return (
<>
<h1>Exmaple UseRecuer wiht Deep Component with dispatch</h1>
count is {state.count} and email is {state.email}
<button onClick={() => dispatch({ type: 'ADD' })}>Add</button>
<Child dispatch={dispatch} />
</>
);
}

function Child(props) {
const [email, setEmail] = useState('');
const { dispatch } = props;
return (
<>
<input
type="text"
name="email"
onChange={(e) => setEmail(e.target.value)}
/>
<button onClick={() => dispatch({ type: 'SUB' })}>SUB</button>
<button
onClick={() => dispatch({ type: 'EMAIL_CHANGE', payload: email })}
>
Change EMail
</button>
</>
);
}

TODO App with useReducer

import React, { useState, useReducer, useRef } from 'react';

//https://www.youtube.com/watch?v=p54lj4vM_LA

//useRedcuer

//1. Init State
const initState = {
job: '',
jobs: [],
};

//2. Actions
const SET_JOB = 'set_job';
const ADDJOB = 'add_job';
const DELETE_JOB = 'delete_job';
const UPDATE_JOB = 'update_job';

//3. Reducer
const reducer = (state, action) => {
// console.log('Action', action);
// console.log('Prev State', state);

let newState;
switch (action.type) {
case 'SET_JOB':
return (newState = { ...state, job: action.payload });
break;
case 'ADD_JOB':
return (newState = { ...state, jobs: [...state.jobs, action.payload] });
break;
case 'DELETE_JOB':
const newjobs = [...state.jobs];
newjobs.splice(action.payload, 1); //should be splice not slice
return (newState = { ...state, jobs: newjobs });
break;
default:
return state;
}
// console.log('New State', newState);
return newState;
};
//4. Dispatch

export default function UseReducerWithToDoApp() {
const [state, dispatch] = useReducer(reducer, initState);

const inputRef = useRef();

const { job, jobs } = state;
// console.log('state raja', state);

const handleSubmit = (e) => {
dispatch({
type: 'ADD_JOB',
payload: job,
});
dispatch({
type: 'SET_JOB',
payload: '',
});
inputRef.current.focus();
};

const handleDelete = (job) => {
console.log("deelte job", job)
dispatch({
type: 'DELETE_JOB',
payload: job,
});
inputRef.current.focus();
};
return (
<div style={{ padding: '20px' }}>
<h3>ToDo App With UseReducer</h3>
<input
type="text"
value={job}
placeholder="Enter to do.."
ref={inputRef}
onChange={(e) => {
// e.target.value;
dispatch({ type: 'SET_JOB', payload: e.target.value });
}}
/>
<button onClick={handleSubmit}>Add</button>
<p>{JSON.stringify(jobs, 2, '')}</p>
<ul>
{jobs.map((job, index) => {
return (
<li>
{job} &times;<span onClick={() => handleDelete(job)}>delete</span>
</li>
);
})}
</ul>
</div>
);
}

COMPONENT UNMOUNT

We will focus on useState and useEffect in this article.

- In hooks we use return in useEffect 

useEffect(()={
console.log('API CALL')
return()={
//do cleanup
};
},[])

Q12. #Additional Hooks

We will not be covering Additional Hooks at all as this article would be way too long but you are encouraged to read more about them on Additional Hooks

  • useReducer, alternative to useState, it accepts a reducer and returns a pair with the current state and a dispatch function
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:
throw new Error();
}
}

function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}

MEMO

MEMO :
javascript have the feature to saver result in memory
if we call the same function agian and again with out changing parameters

Ex:
function Add(a,b) {
return a+b
}

Add(20,30)

there are some funcation in the component that are been called again and
again which degrade the memory. the solution is useMemo
-------------------memo
import React, {useState, memo} from 'react'
const Child = memo(function() {
console.log("Child is called")
return (
<div>Child
</div>
)
})
//why child gets called as we are not passing any value
export default function Memo() {
const [count, setcount] = useState(0)
const submitHandle = () =>{
// console.log("Count", count)
setcount(count+1)
}

return (
<div>
<p>Parent Count : {count}</p>
<button onClick={submitHandle}> Click Memo</button>
<Child />
</div>
)
}

UseMemo

--useMemo
import React, {useState, memo, useMemo} from 'react'
//Memorise the Value not funcation
//chnage in local number should not chagne the function largeNumber
//https://www.youtube.com/watch?v=P_YwL0B8k7k&list=PLp18NAIKHWnvpLpioGs6ZAiMlpfx49KOz&index=14
//https://www.youtube.com/watch?v=Fp4PlygdV5E&t=980s

const array = [1,2,3,4,5,6,7,8,9];
const Child = memo(function() {
console.log("Child is called")
return ( <div>Child</div>
)
})


///exoprt default memo(Child) //if child func is no the other page
//why child gets called as we are not passing any value
export default function UseMemo() {
const [localvalue, setlocalvalue] = useState(0)

//old way
function largeNumber(){
console.log("called many time");
return Math.max(...array);
}

//new way with useMemo
const memoizeValue = useMemo(function multiply() {
console.log("called one time");
largeNumber()
}, [largeNumber])

//https://www.youtube.com/watch?v=P_YwL0B8k7k&list=PLp18NAIKHWnvpLpioGs6ZAiMlpfx49KOz&index=14

return (
<div>
<p>Local Value : {localvalue}</p>
<button onClick={()=>setlocalvalue(localvalue+1)}> Click UseMemo</button>

{/* <h1>Largest number {largeNumber()}</h1> */} //1
<h1>Largest number {memoizeValue}</h1> //2

{/* <Child number ={largeNumber}/> */} //3
{/* <Child number ={memoizeValue}/> */} //dont use it //4

</div>
)
}

UseCallback

useMemo and useCallback both are smiller 

1. main diffrence is useMemo return memorized value and

2. useCallback return memorized function - passing function as props

React.memo have issue that it only works on the value but not on function.
Solution is useCallback

useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).

useCallback example 1



1st way
const Child = memo(function (props){
console.log("I am rendering");
return <h1>"I am a child</h1>;
});


2nd way
const Child = (props) => {
console.log("I am rendering");
return <h1>"I am a child</h1>;
};
export default memo(Child)


-----------start-----------------
export default function App(){
const [localvalue, setLocalValue] = useState(0);

function multiplication() {}

const memiozedFunc = useCallback(multiplication,[]); //useCallback
[] - it should it will fun only first time,
[count] - runs when the count value changes

return(
<div>
<p>{LocalValue}</p>
<button onClick={() => setLocalValue(localValue +1)}>Change</button> //1

<Child func={multiplication} />// passing function as props //2
</div>
)

if we dont use useCallback the child will still render one click of button.
even if we have use the memo to stop rerender.
---useCallback - example 2
import React, {useState, memo, useCallback} from 'react'
//Memorise the function
//this is used in case, when we are passing funcation in child componet
// so even though there is no change the child get render, dispite use of the memo
// fix is to useCallback
//https://www.youtube.com/watch?v=Fp4PlygdV5E&t=980s
const Child = memo(function() {
console.log("Child is called")
return (
<div>Child
</div>
)
})
//why child gets called as we are not passing any value

export default function UseCallBack() {
const [count, setcount] = useState(0)

const submitHandle = () =>{
// console.log("Count", count)
setcount(count+1)
}

const somefunc = () =>{
// console.log("Count", count)
}

const memoizefunc = useCallback(somefunc, [])
//excepts 2 aregumer and return new funcation

return (
<div>
<p>Parent Count : {count}</p>
<button onClick={submitHandle}> Click UseCallBack</button>

{/* <Child somefun={somefun}/> part 1 before usecallsback */}
<Child somefun={memoizefunc}/>
</div>
)
}
//other way to do
// const [childNum, setchildNum] = useState(0)
// const memoizefunc = useCallback(num=>somefunc(num), [])
// <Child num={childNum} />

UseReducer

---useReducer
import React, {useReducer} from 'react'
function reducer(state, action){
console.log(state, action.text)
switch (action.type) {
case "add-todo":
return {
todos: [...state.todos, {text:action.text, completed:false}]
};
case "delete-todo":
return {
// todos: state.todos.filter(item=>item!=})
};
default:
return state;
}
}

export default function UseReducer() {
const [{todos}, dispatch] = useReducer(reducer, {todos:[]});//useReducer2
const [text, settext] = React.useState()

const onSubmitHandler = (e) = >{
e.preventDefault();
dispatch({type:"add-todo", text});
settext("");
}

return (
<div>
<form onSubmit={onSubmitHandler}>
<h1>Adding value - useReducer</h1>
<input value={text} onChange={(e)=> settext(e.target.value)} />
{todos.map((t,idx)=>{
return <div key={t.text} onClick={()=>dispatch({type:"delete-todo", idx})}>{t.text}</div>
})}
<pre>{JSON.stringify(todos, null, 2)}</pre>
</form>
</div>
)
}
#

UseContextReducer

--useContextReducer
import React, {useContext,useReducer} from 'react'

const Context = React.createContext(); //useContext 1

function Child() {
return <div> <GrandChild /></div>
}

function GrandChild() {
const myname = useContext(Context) //useContext3
console.log("mystoredetials", myname)
return <div>GrandChildCount : {myname}</div>//useContext4
}

const initialState = 0; //useReducer1
function reducer(state, action){
console.log(state, action)
switch (action) {
case "increment":
return state +1;
case "decrement":
return state -1;
case "reset":
return initialState
default:
throw new Error();
}
}

export default function UseContextReducer() {
const [count, dispatch] = useReducer(reducer, initialState);//useReducer2
return (
//useContext2, useReducer4
<Context.Provider value={count}>
<div>
<h1>UseContext and UseReducer</h1>
{/* useReducer3 */}
<button onClick={() => dispatch('increment')}>Increment</button>
<button onClick={() => dispatch('decrement')}>Decrement</button>
<button onClick={() => dispatch('reset')}>Reset</button>
{/* useReducer4 */}
<div>ParentCount : {count}</div>
<Child />
</div>
</Context.Provider>
)
}


Custom Hooks


<<<<Simple component without custom hooks>>>>
-------------------APICall.js-------------------------------------------------

import React, {useEffect, useState} from 'react'
// What is a custom hook?
// A custom Hook is a JavaScript function whose name starts with "use" and that may call other Hooks.
//A custom hook allows you to extract some components logic into a reusable function.
export default function APICall() {
const [data, setData] = useState([])
const [loading, setLoading] = useState(true)

function callApi(){
fetch("https://jsonplaceholder.typicode.com/users")
.then(res=>res.json())
.then(data=>{
setData(data);
setLoading(false)
})
}

useEffect(()=>{
callApi()
},[])

return (
<div>
{loading? <p>Loading....</p>:null}
{JSON.stringify(data)}
</div>
)
}


-------------------useApi.js-----------------------------------------------------

<<<<Simple component with custom hooks>>>>
import React, {useEffect, useState} from 'react'

// What is a custom hook?
// A custom Hook is a JavaScript function whose name starts with "use" and that may call other Hooks.
//A custom hook allows you to extract some components logic into a reusable function.
const useApi = (URL) =>{ //is we use in another page then this can be resuale
const [data, setData] = useState([])
const [loading, setLoading] = useState(true)

function callApi(URL){
fetch(URL)
.then(res=>res.json())
.then(data=>{
setData(data);
setLoading(false)
})
}

useEffect(()=>{
callApi()
},[])

return {loading,data}
}

-----------------------CustomeHooksApiMain.js------------------------------------
// import useApi from './useApi'
export default function CustomeHooksApiMain() {
const {loading, data} = useApi("https://jsonplaceholder.typicode.com/users")

return (
<div>
{loading? <p>1Loading....</p>:null}
{JSON.stringify(data)}
</div>
)
}

Q13. Prop Drilling

Prop Drilling is the process by which you pass data from one part of the React Component tree to another by going through other parts that do not need the data but only help in passing it around. PARENT to child

This can cause components to re-render when it is not necessary to, also in large applications, this can have significant performance issues.

Q14. Lifting props and state

We should lift any shared state up to their closest common ancestor. This way, one state can be shared between multiple child components by passing them down via props. For example, if we want to build a calculator for converting lengths, we can write the following:

https://stackblitz.com/edit/react-interview-demo-r6fieu?file=src%2FLesson2Propslift.js

Props drillind ChildA - ChildB - ChildC

passing props form ChildC to ChildA

==>ChildA
-->function ChildA(props:Props)

const onShowAddCard = (position: number): void => { //6
console.log(position)
}

return (
<Card onShowAddCard1={onShowAddCard}/> //5
)



==>ChildB
type Props = {
onShowAddCard1: (position: number) => void //4
}
-->function ChildB(props:Props)
const { data, onShowAddCard1 } = props
return (
<ChildC onShowAddCard2={onShowAddCard1} /> //3
)



==>ChildC
type Props = {
onShowAddCard2: (position: number) => void //2
}

export default function ChildC(props:Props) {
const { data, onShowAddCard2 } = props //1

const [name, setName] = useState()
const [pwd, setPwd] = useState()

const handleChange = (e) =>{
if(e.target.name==="userid"){
setName(e.target.value);
}else{
setPwd(e.target.value);
}
}

const handleSubmit = (e) =>{
e.preventDefault()
props.onShowAddCard2(name) ///lifting state up //0
console.log("the name and passsword is", name, pwd)
}
return (
<div>
<form onSubmit={handleSubmit}>
<h1>Lifting props and state</h1>
<input type="text" name="userid" value={name} onChange={handleChange} />
<input type="text" name="password" value={name} onChange={handleChange} />
</form>
</div>
)

The advantage of lifting the states up to the parent component is that we only have to keep one copy of the state. Also, we don’t have to repeat the processing of the states in different child components.

The values of the inputs stay in sync because they’re computed from the same state.

https://www.youtube.com/watch?v=Fp4PlygdV5E (interview question)

QA. ADVANCED GUIDES

1. Code-Splitting —

splitting the code into small parts, when react compile it will create a single bundle which is very large that is a problem when we have a huge project. Also when users visit only one page then do we need to load the pages. so React introduced dynamic import to split code into a different bundle also called lazy loading, this requires a fallback page to load.

Chunking in Lazy Loading

Chunking is a technique used in lazy loading to load data or resources in smaller, manageable chunks instead of loading everything at once. This can help improve performance and reduce memory usage, especially when dealing with large datasets or heavy resources.

Type 1

import {add} from './math'console.log(add(20,10);Function: New way - Run code only when requiredimport('./math').then((result)=>{
console.log('result', result.add(10,20))
})

Type 2

Components - use lazy load
1. create simple Home.js class
2. App.js - <Home/> //old way
3. App.js - with lazy loading
import React, { Suspense } from 'react';const Home = React.lazy(() => import('./Home'));function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<Home/>
</Suspense>
</div>
);
}
4. Add 1000 lines to text to see the loading in Home.js

3. Error Boundaries — Already completed

4. 5. Fragments

A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
You can use <></> the same way you’d use any other element except that it doesn’t support keys or attributes.

6. Higher-Order Components

This is a function that receives a component as an argument and returns a newly updated component. Used for reusability of code.

import React from "react";
import ReactDOM from "react-dom";
//hoc example
const innerComponent = props => (
<div>
<h2> Inner component title</h2>
<p>{props.name}</p>
</div>
);

const hocCreator = WrappedComponent => {
return props => (
<div>
<h1>Outer Wrapper header</h1>
<WrappedComponent {...props} />
</div>
);
};
const FinalHigherComponent = hocCreator(innerComponent);

ReactDOM.render(
<FinalHigherComponent name="jason" isValid={false} />,
document.getElementById("root")
);

OUTPUT
Outer Wrapper header
Inner component title
jason

7. JSX In-Depth :

Big topic please refer to JSX In Depth — React (reactjs.org)

Fundamentally, JSX just provides syntactic sugar for the React.createElement(component, props, ...children) function. The JSX code:
Button in JSX:
<MyButton color="blue" shadowSize={2}> Click Me</MyButton>
compiles into:
React.createElement(
MyButton,
{color: 'blue', shadowSize: 2},
'Click Me'
)
Div in JSX:
<div className="sidebar" />
compiles into:
React.createElement(
'div',
{className: 'sidebar'}
)
import React from 'react';
import CustomButton from './CustomButton';
function WarningButton() {
// return React.createElement(CustomButton, {color: 'red'}, null); return <CustomButton color="red" />;
}
Testing:
Babel · The compiler for next generation JavaScript (babeljs.io)
2. User-Defined Components Must Be Capitalized
When an element type starts with a lowercase letter, it refers to a built-in component like <div> or <span> and results in a string 'div' or 'span' passed to React.createElement.
3. Using Dot Notation for JSX Type
import React from 'react';

const MyComponents = {
DatePicker: function DatePicker(props) {
return <div>Imagine a {props.color} datepicker here.</div>;
}
}

function BlueDatePicker() {
return <MyComponents.DatePicker color="blue" />;}
4. Props Default to “True”If you pass no value for a prop, it defaults to true. These two JSX expressions are equivalent:
<MyTextBox autocomplete />

<MyTextBox autocomplete={true} />
5. Spread AttributesIf you already have props as an object, and you want to pass it in JSX, you can use ... as a “spread” operator to pass the whole props object. These two components are equivalent:function App1() {
return <Greeting firstName="Ben" lastName="Hector" />;
}

function App2() {
const propsObj = {firstName: 'Ben', lastName: 'Hector'};
return <Greeting {...propsObj} />;}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
const Button = props => {
const { kind, ...other } = props;
const className = kind === "primary" ? "PrimaryButton" : "SecondaryButton";
return <button className={className} {...other} />;
};

const App = () => {
return (
<div>
<Button kind="primary" onClick={() => console.log("clicked!")}>
Hello World!
</Button>
</div>
);
6. JavaScript Expressions as Children
function Item(props) {
return <li>{props.message}</li>;}

function TodoList() {
const todos = ['finish doc', 'submit pr', 'nag dan to review'];
return (
<ul>
{todos.map((message) => <Item key={message} message={message} />)} </ul>
);
}
<div>{showHeader && <Header />}
{props.messages.length >0 &&<MessageList messages={props.messages}/>
}
</div>

8. Other Question :

  • Check next.js, gatsby to see more. how spread thing across different pages rather than single page application.
1. LoadBalancer can be used to scalse and handle large request
2. Passing child to parent - use the callback function, and context, redux, next.js contex is easy

3. sharing data accross two diffrent react application - use the cookies, localstorage or api to send and get data. Session storage
4. Custom hooks- learn more abou this.
5. No erroboundary for functional component/hooks, only their in class component.
6. how to setup - used based on the layout, all dynamic componet in layout
7. user Authenitcation - JWT (JSON Web token), client and server passing data and store in globalstate, like redux, context API. Replace all the redux with context api and useReducer.
8. Serverless function (lambda/function) are store in API folder in
next.js, gatsby

9. Portals

Sometimes we need to write code outside the root element. Used to create modal or jquery, which are not on the Jquery.

Most applications contain modals, toasts, and other elements that require escaping the default DOM hierarchy. Portals provide a convenient way to render components in a separate DOM node. The candidate should be able to explain how portals work and their ideal use cases.

Portal is React’s recommended way to render children components into a DOM node that exists outside the DOM hierarchy of the parent component.

A portal is created by calling ReactDom‘s createPortal function.

ReactDOM.createPortal(content, containerElement);

Youtube
https://www.youtube.com/watch?v=538Zu3Y0xTA -
https://codesandbox.io/s/00254q4n6p?file=/src/index.js:277-298
>>>>>>index.html

<div id="root"></div>
<div id="other-root"></div>

>>>>>>App.js
import {Other} form "./Other"
return(
<Other />
)

>>>>>>Other.js
import React from 'react'
import { ReactDOM } from 'react-dom'

export default function Other() {
return (
<div>
{ReactDOM.createPortal(
<h1>Other portal</h1>,
document.getElementById('other-root')
)}
</div>
)
}

10. What is React Profiler and what is it used for?

Optimizations are a key part of every application. Knowing which tools to use can be a huge productivity boost. This is a more advanced question that an interview might ask to understand the candidate’s ability to diagnose and optimize a React application.

React Profiler is a means to measure the cost of rendering in a React application. The purpose of this component is to help developers identify parts of the application that are slow and may benefit from further optimizations.

The Profiler can be added anywhere in the component tree to measure its rendering cost. For example, the code below shows how the Profiler component is used to measure the rendering cost of the Navigation component and its descendants:

render(
<App>
<Profiler id="Navigation" onRender={callback}>
<Navigation {...props} />
</Profiler>
<Main {...props} />
</App>
);

11. React Without ES6

Without ES6

class SayHello extends React.Component {
constructor(props) {
super(props);
this.state = {message: 'Hello!'};
// This line is important!
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
alert(this.state.message);
}

render() {
// Because `this.handleClick` is bound, USE it as an event handler.
return (
<button onClick={this.handleClick}>
Say hello
</button>
);
}
}

With ES6

If the boilerplate code is too unattractive to you, you may enable the experimental Class Properties syntax proposal with Babel:

class SayHello extends React.Component {
constructor(props) {
super(props);
this.state = {message: 'Hello!'};
}
// WARNING: this syntax is experimental!
// Using an arrow here binds the method:
handleClick = () => {
alert(this.state.message);
}
render() {
return (
<button onClick={this.handleClick}>
Say hello
</button>
);
}
}

12. React Without JSX

JSX is not a requirement for using React. Using React without JSX is especially convenient when you don’t want to set up compilation in your build environment.

Anything we do with JSX we can do with plain javascript by calling React.createElement(component, props, ...children).

return <div>Hello {this.props.toWhat}</div>;  
to
return React.createElement('div', null, `Hello ${this.props.toWhat}`);



ReactDOM.render(
<Hello toWhat="World" />,
document.getElementById('root')
);
to
ReactDOM.render(
React.createElement(Hello, {toWhat: 'World'}, null),
document.getElementById('root')
);

When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called reconciliation.

https://dev.to/teo_garcia/understanding-rendering-in-react-i5i

The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function.

A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.

Render props:
helps in re-usiblity of loading and list

Take a look at example.
// src/containers/App/index.jsx

import React, { createContext } from 'react';
import List from '../../Components/List';

const App = () => (
<List
apiPath="//dog.ceo/api/breeds/list/all"
render={ // 1,render as props
({list, isLoading}) => isLoading ? <div>now loading...</div> : <div>Done!</div>
}/>
// So, Key point is here, as you can see you can use render as a props.

)

export default App;



-------------------------------------------------------------
// src/components/List/List.jsx
import React, { Component } from 'react';

export default class List extends Component {
constructor(props) {
super(props);
this.state = {
list: [], //2
isLoading: false
}
}

fetchApi = async () => {
const res = await fetch(this.props.apiPath);
const json = await res.json();

await this.setState({
list: json, //3
isLoading: false,
});
}

componentDidMount() {
this.setState({ isLoading: true }, this.fetchApi);
}

render() {
return this.props.render(this.state) //4, Especially, this line.
}
}


Q) Do Hooks replace render props and higher order components?
ans) Both render props and higher-order components render only a
single child but in most of the cases Hooks are a simpler way to
serve this by reducing nesting in your tree.

Static type checkers like Flow and TypeScript identify certain types of problems before you even run your code. They can also improve developer workflow by adding features like auto-completion. For this reason, we recommend using Flow or TypeScript instead of PropTypes for larger codebases.

Flow

Flow is a static type checker for your JavaScript code. It is developed at Facebook and is often used with React. It lets you annotate the variables, functions, and React components with a special type syntax, and catch mistakes early. You can read an introduction to Flow to learn its basics.

TypeScript

TypeScript is a programming language developed by Microsoft. It is a typed superset of JavaScript, and includes its own compiler. Being a typed language, TypeScript can catch errors and bugs at build time, long before your app goes live. You can learn more about using TypeScript with React here.

Type checking With PropTypes

Flow or TypeScript help to typecheck your whole application. But even if you don’t use those, React has some built-in type-checking abilities.

To run type-checking on the props for a component, you can assign the special propTypes property: (ALERT)

Class Component :


import PropTypes from 'prop-types';


class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}

Greeting.propTypes = {
name: PropTypes.string
};

Functional Component :

import PropTypes from 'prop-types'

function HelloWorld({ name }) {
return (
<div>Hello, {name}</div>
)
}

HelloWorld.propTypes = {
name: PropTypes.string
}


export default HelloWorldComponent
  1. How to improve performance of react appliation?
  2. Archiecture design for react.js. Approach to build React application?
  3. Bug Tracking on the react appliation on the live client.
  4. Tools used in the react application?
  5. Session data, if the session expired in 1 hours.

Try it on CodePen

Useful Link

How to improve performance of react appliation?

first, profile into the app and check which area is creating an issue.

Unnecessary re-rendering — stop this will shouldComonetUpdate, PureComponet, and React.memo

if package size is large then use the lazy loading. React.lazy

Optimize the application are API level

Check is some new joiner have used the wrong methods to update the state or state are updated directly.

Is vedio/Adio is loading slowly, fined if this is CDN issues!

use the arrow function or normal function instead of class function

What is event in react?

Events are triggered reactions to specific actions like mouse click, key press, etc. These are similar to JavaScript and HTML events.

How to create events in React?

function clickHandle(e){
console.log(e.target.value)
}
<div onClick={clickHandle} />

Which is the best UI for ReactJS?


UI frameworks like
MUI (Material UI),
React Bootstrap,
React Redux, and
Semantic UI

are some of the best UIs for ReactJS.

Ant Design,
Chakra UI,
Fluent UI, and
Evergreen are also popular UIs.

Can AJAX be used with react?

Yes, any AJAX library like Axios, and jQuery Ajax, can be used with React easily.

How is routing in React diffrnet from conventional routing?
> pages : each view is like new file in conventional routing while
it is consideted as single HTML entity in React.

> Navigation : In conventional routing, user need to move across the pages
to view the page. In react, view are not refreshed as objects are
re-issued to create new views.

What is the use of second argument that is passed to setState? Is it optional?
> Yes, its otional argument, Since setState is asynchronous, it takes
another callback funcation, which re-renders the page.

Avoid the requiremnt of binding(class) when using react?
> Arrow fuction event handler
> function component along with Hooks.

Q100: ReactJS project test?

TODO-LIST project

  1. Build from scratch — npx create-react-app my-app
  2. use the arrow function
  3. Don't spend time in CSS
  4. Write some test cases in Jest.

Q101: ReactJS project Type?

  1. TODO list app — some part on this- update the list
  2. Searchable dropdown
  3. Deeply nested dropdown

dropdown list like below

Take-home test:

Q101: ReactJS project test?

TOP 10 MISTAKES

  1. FOLDER STRUCTURE — CSS/UNIT TEST ALONG WITH CLASS/TEST
  2. MONOLITHIC APPLICATION — FRAGMENT, LOWER LEVEL COMPONENT, RE-USABLE COMPONENT. FLEXIBLE, MAINTAINABLE, NOT MORE THAN 100 LINE
  3. BUSSINESS LOGIC IN REUABLE COMPOENT
  4. REDUX TO MANAGE ALL THE STATES — EXAMPLE DROP DOWN
  5. NOT USING RIGHT LIFECYCLE METHOD
  6. NOT HAVING UNIT TESTS
  7. NOT PLANNING BEFORE CODING
  8. NOT KEEPING UP WITH UPGRADES
  9. INCORRECT PROPTYPE EX <Comp x=”2” /> and <Comp x={2} />

— — — — — — — — — — — — — — — — — — — — — — — —

REACT CheetSheet

Table of Contents

React Fundamentals

Essential React Hooks

Hooks and Performance

Advanced React Hooks

React Fundamentals

JSX Elements

React applications are structured using a syntax called JSX. This is the syntax of a basic JSX element

/* 
JSX allows us to write in a syntax almost identical to plain HTML.
As a result, JSX is a powerful tool to structure our applications.
JSX uses all valid HTML tags (i.e. div/span, h1-h6, form/input, img, etc).
*/
<div>Hello React!</div>/*
Note: this JSX would not be visible because it is needs to be rendered by our application using ReactDOM.render()
*/

JSX is the most common way to structure React applications, but JSX is not required for React

/* JSX is a simpler way to use the function React.createElement()
In other words, the following two lines in React are the same: */
<div>Hello React!</div>; // JSX syntaxReact.createElement("div", null, "Hello React!"); // createElement syntax

JSX is not understood by the browser. JSX needs to be compiled to plain JavaScript, which the browser can understand.

The most commonly used compiler for JSX is called Babel

/* 
When our project is built to run in the browser, our JSX will be converted by Babel into simple React.createElement() function calls.
From this...
*/
const greeting = <div>Hello React!</div>;
/* ...into this: */
("use strict");
const greeting = /*#__PURE__*/ React.createElement("div", null, "Hello React!");

JSX differs from HTML in several important ways

/*
We can write JSX like plain HTML, but it's actually made using JavaScript functions.
Because JSX is JavaScript, not HTML, there are some differences:
1) Some JSX attributes are named differently than HTML attributes. Why? Because some attribute words are reserved words in JavaScript, such as 'class'. Instead of class, JSX uses 'className'. Also, because JSX is JavaScript, attributes that consist of multiple words are written in camelcase:
*/
<div id="header">
<h1 className="title">Hello React!</h1>
</div>
/*
2) JSX elements that consist of only a single tag (i.e. input, img, br elements) must be closed with a trailing forward slash to be valid (/):
*/
<input type="email" /> // <input type="email"> is a syntax error /*
3) JSX elements that consists of an opening and closing tag (i.e. div, span, button element), must have both or be closed with a trailing forward slash. Like 2), it is a syntax error to have an unterminated element.
*/
<button>Click me</button> // <button> or </button> is a syntax error
<button /> // empty, but also valid

Inline styles can be added to JSX elements using the style attribute

Styles are updated within an object, not a set of double quotes, as with HTML

Note that style property names must be also written in camelcase

/* 
Properties that accept pixel values (like width, height, padding, margin, etc), can use integers instead of strings.
For example: fontSize: 22. Instead of: fontSize: "22px"
*/
<h1 style={{ color: "blue", fontSize: 22, padding: "0.5em 1em" }}>
Hello React!
</h1>

JSX elements are JavaScript expressions and can be used as such

JSX gives us the full power of JavaScript directly within our user interface

/* 
JSX elements are expressions (resolve to a value) and therefore can be assigned to plain JavaScript variables...
*/
const greeting = <div>Hello React!</div>;
const isNewToReact = true;// ... or can be displayed conditionally
function sayGreeting() {
if (isNewToReact) {
// ... or returned from functions, etc.
return greeting; // displays: Hello React!
} else {
return <div>Hi again, React</div>;
}
}

JSX allows us to insert (or embed) simple JavaScript expressions using the curly braces syntax

const year = 2021;/* We can insert primitive JS values (i.e. strings, numbers, booleans) in curly braces: {} */
const greeting = <div>Hello React in {year}</div>;
/* We can also insert expressions that resolve to a primitive value: */
const goodbye = <div>Goodbye previous year: {year - 1}</div>;
/* Expressions can also be used for element attributes */
const className = "title";
const title = <h1 className={className}>My title</h1>;
/* Note: trying to insert object values (i.e. objects, arrays, maps) in curly braces will result in an error */

JSX allows us to nest elements within one another, like we would HTML

/* 
To write JSX on multiple lines, wrap in parentheses: ()
JSX expressions that span multiple lines are called multiline expressions
*/
const greeting = (
// div is the parent element
<div>
{/* h1 and p are child elements */}
<h1>Hello!</h1>
<p>Welcome to React</p>
</div>
);
/* 'parents' and 'children' are how we describe JSX elements in relation
to one another, like we would talk about HTML elements */

Comments in JSX are written as multiline JavaScript comments, written between curly braces

const greeting = (
<div>
{/* This is a single line comment */}
<h1>Hello!</h1>
<p>Welcome to React</p>
{/* This is a
multiline
comment */}
</div>
);

All React apps require three things:

  1. ReactDOM.render(): used to render (show) our app by mounting it onto an HTML element
  2. A JSX element: called a “root node”, because it is the root of our application. Meaning, rendering it will render all children within it
  3. An HTML (DOM) element: Where the app is inserted within an HTML page. The element is usually a div with an id of “root”, located in an index.html file
// Packages can be installed locally or brought in through a CDN link (added to head of HTML document)
import React from "react";
import ReactDOM from "react-dom";
// root node (usually a component) is most often called "App"
const App = <h1>Hello React!</h1>;
// ReactDOM.render(root node, HTML element)
ReactDOM.render(App, document.getElementById("root"));

Components and Props

JSX can be grouped together within individual functions called components

There are two types of components in React: function components and class components

Component names, for function or class components, are capitalized to distinguish them from plain JavaScript functions that do not return JSX

import React from "react";/*  
Function component
Note the capitalized function name: 'Header', not 'header'
*/
function Header() {
return <h1>Hello React</h1>;
}
// Function components which use an arrow function syntax are also valid
const Header = () => <h1>Hello React</h1>;
/*
Class component
Class components have more boilerplate (note the 'extends' keyword and 'render' method)
*/
class Header extends React.Component {
render() {
return <h1>Hello React</h1>;
}
}

Components, despite being functions, are not called like ordinary JavaScript functions

Components are executed by rendering them like we would JSX in our app

// Do we call this function component like a normal function?// No, to execute them and display the JSX they return...
const Header = () => <h1>Hello React</h1>;
// ...we use them as 'custom' JSX elements
ReactDOM.render(<Header />, document.getElementById("root"));
// renders: <h1>Hello React</h1>

The huge benefit of components is their ability to be reused across our apps, wherever we need them

Since components leverage the power of JavaScript functions, we can logically pass data to them, like we would by passing it one or more arguments

/* 
The Header and Footer components can be reused in any page in our app.
Components remove the need to rewrite the same JSX multiple times.
*/
// IndexPage component, visible on '/' route of our app
function IndexPage() {
return (
<div>
<Header />
<Hero />
<Footer />
</div>
);
}
// AboutPage component, visible on the '/about' route
function AboutPage() {
return (
<div>
<Header />
<About />
<Testimonials />
<Footer />
</div>
);
}

Data passed to components in JavaScript are called props

Props look identical to attributes on plain JSX/HTML elements, but you can access their values within the component itself

Props are available in parameters of the component to which they are passed. Props are always included as properties of an object

/* 
What if we want to pass custom data to our component from a parent component?
For example, to display the user's name in our app header.
*/
const username = "John";/*
To do so, we add custom 'attributes' to our component called props
We can add many of them as we like and we give them names that suit the data we pass in.
To pass the user's name to the header, we use a prop we appropriately called 'username'
*/
ReactDOM.render(
<Header username={username} />,
document.getElementById("root")
);
// We called this prop 'username', but can use any valid identifier we would give, for example, a JavaScript variable
// props is the object that every component receives as an argument
function Header(props) {
// the props we make on the component (username)
// become properties on the props object
return <h1>Hello {props.username}</h1>;
}

Props must never be directly changed within the child component.

Another way to say this is that props should never be mutated, since props are a plain JavaScript object

/* 
Components should operate as 'pure' functions.
That is, for every input, we should be able to expect the same output.
This means we cannot mutate the props object, only read from it.
*/
// We cannot modify the props object :
function Header(props) {
props.username = "Doug";
return <h1>Hello {props.username}</h1>;
}
/*
But what if we want to modify a prop value that is passed to our component?
That's where we would use state (see the useState section).
*/

The children prop is useful if we want to pass elements / components as props to other components

// Can we accept React elements (or components) as props?
// Yes, through a special property on the props object called 'children'
function Layout(props) {
return <div className="container">{props.children}</div>;
}
// The children prop is very useful for when you want the same
// component (such as a Layout component) to wrap all other components:
function IndexPage() {
return (
<Layout>
<Header />
<Hero />
<Footer />
</Layout>
);
}
// different page, but uses same Layout component (thanks to children prop)
function AboutPage() {
return (
<Layout>
<About />
<Footer />
</Layout>
);
}

Again, since components are JavaScript expressions, we can use them in combination with if-else statements and switch statements to conditionally show content

function Header() {
const isAuthenticated = checkAuth();
/* if user is authenticated, show the authenticated app, otherwise, the unauthenticated app */
if (isAuthenticated) {
return <AuthenticatedApp />;
} else {
/* alternatively, we can drop the else section and provide a simple return, and the conditional will operate in the same way */
return <UnAuthenticatedApp />;
}
}

To use conditions within a component’s returned JSX, you can use the ternary operator or short-circuiting (&& and || operators)

function Header() {
const isAuthenticated = checkAuth();
return (
<nav>
{/* if isAuth is true, show nothing. If false, show Logo */}
{isAuthenticated || <Logo />}
{/* if isAuth is true, show AuthenticatedApp. If false, show Login */}
{isAuthenticated ? <AuthenticatedApp /> : <LoginScreen />}
{/* if isAuth is true, show Footer. If false, show nothing */}
{isAuthenticated && <Footer />}
</nav>
);
}

Fragments are special components for displaying multiple components without adding an extra element to the DOM

Fragments are ideal for conditional logic that have multiple adjacent components or elements

/*
We can improve the logic in the previous example.
If isAuthenticated is true, how do we display both the AuthenticatedApp and Footer components?
*/
function Header() {
const isAuthenticated = checkAuth();
return (
<nav>
<Logo />
{/*
We can render both components with a fragment.
Fragments are very concise: <> </>
*/}
{isAuthenticated ? (
<>
<AuthenticatedApp />
<Footer />
</>
) : (
<Login />
)}
</nav>
);
}
/*
Note: An alternate syntax for fragments is React.Fragment:
<React.Fragment>
<AuthenticatedApp />
<Footer />
</React.Fragment>
*/

Lists and Keys

Use the .map() function to convert lists of data (arrays) into lists of elements

const people = ["John", "Bob", "Fred"];
const peopleList = people.map((person) => <p>{person}</p>);

.map() can be used for components as well as plain JSX elements

function App() {
const people = ["John", "Bob", "Fred"];
// can interpolate returned list of elements in {}
return (
<ul>
{/* we're passing each array element as props to Person */}
{people.map((person) => (
<Person name={person} />
))}
</ul>
);
}
function Person({ name }) {
// we access the 'name' prop directly using object destructuring
return <p>This person's name is: {name}</p>;
}

Each React element within a list of elements needs a special key prop

Keys are essential for React to be able to keep track of each element that is being iterated over with the .map() function

React uses keys to performantly update individual elements when their data changes (instead of re-rendering the entire list)

Keys need to have unique values to be able to identify each of them according to their key value

function App() {
const people = [
{ id: "Ksy7py", name: "John" },
{ id: "6eAdl9", name: "Bob" },
{ id: "6eAdl9", name: "Fred" },
];
return (
<ul>
{/* keys need to be primitive values, ideally a unique string, such as an id */}
{people.map((person) => (
<Person key={person.id} name={person.name} />
))}
</ul>
);
}
/* If you don't have some identifier with your set of data that is a unique
and primitive value, use the second parameter of .map() to get each elements index */
function App() {
const people = ["John", "Bob", "Fred"];
return (
<ul>
{/* use array element index for key */}
{people.map((person, i) => (
<Person key={i} name={person} />
))}
</ul>
);
}

Event Listeners and Handling Events

Listening for events on JSX elements versus HTML elements differs in a few important ways

You cannot listen for events on React components; only on JSX elements. Adding a prop called onClick, for example, to a React component would just be another property added to the props object

/*
The convention for most event handler functions is to prefix them with the word 'handle' and then the action they perform (i.e. handleToggleTheme)
*/
function handleToggleTheme() {
// code to toggle app theme
}
/* In HTML, onclick is all lowercase, plus the event handler includes a set of parentheses after being referenced */
<button onclick="handleToggleTheme()">
Toggle Theme
</button>
/*
In JSX, onClick is camelcase, like attributes / props.
We also pass a reference to the function with curly braces.
*/
<button onClick={handleToggleTheme}>
Toggle Theme
</button>;

The most essential React events to know are onClick, onChange, and onSubmit

onClick handles click events on JSX elements (namely on buttons)

onChange handles keyboard events (namely a user typing into an input)

onSubmit handles form submissions from the user

function App() {
function handleInputChange(event) {
/* When passing the function to an event handler, like onChange we get access to data about the event (an object) */
const inputText = event.target.value; // text typed into the input
const inputName = event.target.name; // 'email' from name attribute
}
function handleClick(event) {
/* onClick doesn't usually need event data, but it receives event data as well that we can use */
console.log("clicked!");
const eventType = event.type; // "click"
const eventTarget = event.target; // <button>Submit</button>
}
function handleSubmit(event) {
/*
When we hit the return button, the form will be submitted, as well as when a button with type="submit" is clicked.
We call event.preventDefault() to prevent the default form behavior from taking place, which is to send an HTTP request and reload the page.
*/
event.preventDefault();
const formElements = event.target.elements; // access all element within form
const inputValue = event.target.elements.emailAddress.value; // access the value of the input element with the id "emailAddress"
}
return (
<form onSubmit={handleSubmit}>
<input
id="emailAddress"
type="email"
name="email"
onChange={handleInputChange}
/>
<button onClick={handleClick}>Submit</button>
</form>
);
}

Essential React Hooks

State and useState

useState give us state in a function component

State allows us to access and update certain values in our components over time

Local component state is managed by the React hook useState which gives us both a state variable and a function that allows us to update it

When we call useState we can give our state a default value by providing it as the first argument when we call useState

import React from "react";/* How do you create a state variable?
Syntax: const [stateVariable] = React.useState(defaultValue); */
function App() {
const [language] = React.useState("JavaScript");
/* We use array destructuring to declare state variable. */ return <div>I am learning {language}</div>;
}

Note: Any hook in this section is from the React core library and can be imported individually

import React, { useState } from "react";function App() {
const [language] = useState("javascript");
return <div>I am learning {language}</div>;
}

useState also gives us a ‘setter’ function to update the state after it is created

function App() {
/*
The setter function is always the second destructured value.
The naming convention for the setter function is to be prefixed with 'set'.
*/
const [language, setLanguage] = React.useState("javascript");
return (
<div>
<button onClick={() => setLanguage("python")}>Learn Python</button>
{/*
Why use an inline arrow function here instead of immediately calling it like so: onClick={setterFn()}?
If so, setLanguage would be called immediately and not when the button was clicked by the user.
*/}
<p>I am now learning {language}</p>
</div>
);
}
/* Note: whenever the setter function is called, the state updates,
and the App component re-renders to display the new state.
Whenever state is updated, the component will be re-rendered
*/

useState can be used once or multiple times within a single component

useState can accept primitive or object values to manage state

function App() {
const [language, setLanguage] = React.useState("python");
const [yearsExperience, setYearsExperience] = React.useState(0);
return (
<div>
<button onClick={() => setLanguage("javascript")}>
Change language to JS
</button>
<input
type="number"
value={yearsExperience}
onChange={(event) => setYearsExperience(event.target.value)}
/>
<p>I am now learning {language}</p>
<p>I have {yearsExperience} years of experience</p>
</div>
);
}

If the new state depends on the previous state, to guarantee the update is done reliably, we can use a function within the setter function that gives us the correct previous state

/* We have the option to organize state using whatever is the most appropriate data type, according to the data we're managing */
function App() {
const [developer, setDeveloper] = React.useState({
language: "",
yearsExperience: 0,
});
function handleChangeYearsExperience(event) {
const years = event.target.value;
/* We must pass in the previous state object we had with the spread operator to spread it all of its properties */
setDeveloper({ ...developer, yearsExperience: years });
}
return (
<div>
{/* No need to get previous state here; we are replacing the entire object */}
<button
onClick={() =>
setDeveloper({
language: "javascript",
yearsExperience: 0,
})
}
>
Change language to JS
</button>
{/* We can also pass a reference to the function */}
<input
type="number"
value={developer.yearsExperience}
onChange={handleChangeYearsExperience}
/>
<p>I am now learning {developer.language}</p>
<p>I have {developer.yearsExperience} years of experience</p>
</div>
);
}

If you are managing multiple primitive values, using useState multiple times is often better than using useState once with an object. You don’t have to worry about forgetting to combine the old state with the new state

UPDATE USESTATE:

at 1 and 2, First, Make the copy with spread Operation and update the value
setValues({…values, last name:”Raj”})

USESTATE WITH ARRAY

function UseStateArray() {
const [values, setValues] = React.useState({
language: "",
yearsExperience: 0,
isEmployed: false,
});

function handleClick(event) {
setValues({...values, language:"HINDI"}) //1
setValues((prevState) => { //2
return { ...prevState, isEmployed: !prevState.isEmployed };
// It is essential to return the new state from this function
});
}

return (
<button onClick={handleClick}>Change State</button>
);
}

Side effects and useEffect

useEffect lets us perform side effects in function components. What are side effects?

Side effects are where we need to reach into the outside world. For example, fetching data from an API or working with the DOM

Side effects are actions that can change our component state in an unpredictable fashion (that have cause ‘side effects’)

useEffect accepts a callback function (called the ‘effect’ function), which will by default run every time there is a re-render

useEffect runs once our component mounts, which is the right time to perform a side effect in the component lifecycle

/* What does our code do? Picks a color from the colors array and makes it the background color */
import React, { useState, useEffect } from "react";
function App() {
const [colorIndex, setColorIndex] = useState(0);
const colors = ["blue", "green", "red", "orange"];
/* performing a 'side effect' since we are working with an API.
We are working with the DOM, a browser API outside of React. */
useEffect(() => {
document.body.style.backgroundColor = colors[colorIndex];
});
/* Whenever state is updated, App re-renders and useEffect runs */
function handleChangeColor() {
/* This code may look complex, but all it does is go to the next color in the 'colors' array, and if it is on the last color, goes back to the beginning */
const nextIndex = colorIndex + 1 === colors.length ? 0 : colorIndex + 1;
setColorIndex(nextIndex);
}
return <button onClick={handleChangeColor}>Change background color</button>;
}

To avoid executing the effect callback after each render, we provide a second argument, an empty array

function App() {
/*
With an empty array, our button doesn't work no matter how many times we click it...
The background color is only set once, when the component first mounts.
*/
useEffect(() => {
document.body.style.backgroundColor = colors[colorIndex];
}, []);
/*
How do we not have the effect function run for every state update but still have it work whenever the button is clicked?
*/
return <button onClick={handleChangeIndex}>Change background color</button>;
}

useEffect lets us conditionally perform effects with the dependencies array

The dependencies array is the second argument and if any one of the values in the array changes, the effect function runs again

function App() {
const [colorIndex, setColorIndex] = React.useState(0);
const colors = ["blue", "green", "red", "orange"];
/*
Let's add colorIndex to our dependencies array
When colorIndex changes, useEffect will execute the effect function again
*/
useEffect(() => {
document.body.style.backgroundColor = colors[colorIndex];
/*
When we use useEffect, we must think about what state values
we want our side effect to sync with
*/
}, [colorIndex]);
function handleChangeIndex() {
const next = colorIndex + 1 === colors.length ? 0 : colorIndex + 1;
setColorIndex(next);
}
return <button onClick={handleChangeIndex}>Change background color</button>;
}

useEffect lets us unsubscribe from certain effects by returning a function at the end

function MouseTracker() {
const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
React.useEffect(() => {
// .addEventListener() sets up an active listener...
window.addEventListener("mousemove", handleMouseMove);
/* ...So when we navigate away from this page, it needs to be
removed to stop listening. Otherwise, it will try to set
state in a component that doesn't exist (causing an error)
We unsubscribe any subscriptions / listeners w/ this 'cleanup function')
*/
return () => {
window.removeEventListener("mousemove", handleMouseMove);
};
}, []);
function handleMouseMove(event) {
setMousePosition({
x: event.pageX,
y: event.pageY,
});
}
return (
<div>
<h1>The current mouse position is:</h1>
<p>
X: {mousePosition.x}, Y: {mousePosition.y}
</p>
</div>
);
}

useEffect is the hook to use when you want to make an HTTP request (namely, a GET request when the component mounts)

Note that handling promises with the more concise async/await syntax requires creating a separate function (Why? The effect callback function cannot be async)

const endpoint = "<https://api.github.com/users/reedbarger>";// Using .then() callback functions to resolve promise
function App() {
const [user, setUser] = React.useState(null);
React.useEffect(() => {
fetch(endpoint)
.then((response) => response.json())
.then((data) => setUser(data));
}, []);
}
// Using async / await syntax to resolve promise:
function App() {
const [user, setUser] = React.useState(null);
// cannot make useEffect callback function async
React.useEffect(() => {
getUser();
}, []);
// We must apply async keyword to a separate function
async function getUser() {
const response = await fetch(endpoint);
const data = await response.json();
setUser(data);
}
}

Hooks and Performance

Preventing Re-renders and React.memo

React.memo is a function that allows us to optimize the way our components are rendered

In particular, React.memo performs a process called memoization that helps us prevent our components from re-rendering when they do not need to be (see React.useMemo for more complete definition of memoization)

React.memo helps most with preventing lists of components from being re-rendered when their parent components re-render

/* 
In the following application, we are keeping track of our programming skills. We can create new skills using an input, they are added to the list (shown in the SkillList component). If we click on a skill, it is deleted.
*/
function App() {
const [skill, setSkill] = React.useState("");
const [skills, setSkills] = React.useState(["HTML", "CSS", "JavaScript"]);
function handleChangeInput(event) {
setSkill(event.target.value);
}
function handleAddSkill() {
setSkills(skills.concat(skill));
}
return (
<>
<input onChange={handleChangeInput} />
<button onClick={handleAddSkill}>Add Skill</button>
<SkillList skills={skills} />
</>
);
}
/* But the problem, if you run this code yourself, is that when we type into the input, because the parent component of SkillList (App) re-renders, due to the state being updated on every keystroke, the SkillList is rerendered constantly (as indicated by the console.log) *//* However, once we wrap the SkillList component in React.memo (which is a higher-order function, meaning it accepts a function as an argument), it no longer re-renders unnecessarily when our parent component does. */
const SkillList = React.memo(({ skills }) => {
console.log("rerendering");
return (
<ul>
{skills.map((skill, i) => (
<li key={i}>{skill}</li>
))}
</ul>
);
});
export default App;

Callback functions and useCallback

useCallback is a hook that is used for improving our component performance

Callback functions are the name of functions that are “called back” within a parent component.

The most common usage is to have a parent component with a state variable, but you want to update that state from a child component. What do you do? You pass down a callback function to the child from the parent. That allows us to update state in the parent component.

useCallback functions in a similar way as React.memo. It memoizes callback functions, so it is not recreated on every re-render. Using useCallback correctly can improve the performance of our app

/* Let's keep the exact same App as above with React.memo, but add one small feature. Let's make it possible to delete a skill when we click on it. To do that, we need to filter the skills array according to the skill we click on. For that, we create the handleRemoveSkill function in App */function App() {
const [skill, setSkill] = React.useState("");
const [skills, setSkills] = React.useState(["HTML", "CSS", "JavaScript"]);
function handleChangeInput(event) {
setSkill(event.target.value);
}
function handleAddSkill() {
setSkills(skills.concat(skill));
}
function handleRemoveSkill(skill) {
setSkills(skills.filter((s) => s !== skill));
}
/* Next, we pass handleRemoveSkill down as a prop, or since this is a function, as a callback function to be used within SkillList */
return (
<>
<input onChange={handleChangeInput} />
<button onClick={handleAddSkill}>Add Skill</button>
<SkillList skills={skills} handleRemoveSkill={handleRemoveSkill} />
</>
);
}
/* When we try typing in the input again, we see rerendering in the console every time we type. Our memoization from React.memo is broken! What is happening is the handleRemoveSkill callback function is being recreated everytime App is rerendered, causing all children to be rerendered, too. We need to wrap handleRemoveSkill in useCallback and only have it be recreated when the skill value changes. To fix our app, replace handleRemoveSkill with: const handleRemoveSkill = React.useCallback((skill) => {
setSkills(skills.filter(s => s !== skill))
}, [skills])
Try it yourself!
*/
const SkillList = React.memo(({ skills, handleRemoveSkill }) => {
console.log("rerendering");
return (
<ul>
{skills.map((skill) => (
<li key={skill} onClick={() => handleRemoveSkill(skill)}>
{skill}
</li>
))}
</ul>
);
});
export default App;

Memoization and useMemo

useMemo is very similar to useCallback and is for improving performance, but instead of being for callbacks, it is for storing the results of expensive calculations

useMemo allows us to memoize, or remember the result of expensive calculations when they have already been made for certain inputs.

Memoization means that if a calculation has been done before with a given input, there’s no need to do it again, because we already have the stored result of that operation.

useMemo returns a value from the computation, which is then stored in a variable

/* Building upon our skills app, let's add a feature to search through our available skills through an additional search input. We can add this in a component called SearchSkills (shown above our SkillList).
*/
function App() {
const [skill, setSkill] = React.useState("");
const [skills, setSkills] = React.useState(["HTML", "CSS", "JavaScript"]);
function handleChangeInput(event) {
setSkill(event.target.value);
}
function handleAddSkill() {
setSkills(skills.concat(skill));
}
const handleRemoveSkill = React.useCallback(
(skill) => {
setSkills(skills.filter((s) => s !== skill));
},
[skills]
);
return (
<>
<SearchSkills skills={skills} />
<input onChange={handleChangeInput} />
<button onClick={handleAddSkill}>Add Skill</button>
<SkillList skills={skills} handleRemoveSkill={handleRemoveSkill} />
</>
);
}
// /* Let's imagine we have a list of thousands of skills that we want to search through. How do we performantly find and show the skills that match our search term as the user types into the input ? */
function SearchSkills() {
const [searchTerm, setSearchTerm] = React.useState("");
/* We use React.useMemo to memoize (remember) the returned value from our search operation and only run when it the searchTerm changes */
const searchResults = React.useMemo(() => {
return skills.filter((s) => s.includes(searchTerm));
}, [searchTerm]);
function handleSearchInput(event) {
setSearchTerm(event.target.value);
}
return (
<>
<input onChange={handleSearchInput} />
<ul>
{searchResults.map((result, i) => (
<li key={i}>{result}</li>
))}
</ul>
</>
);
}
export default App;

Advanced React Hooks

Context API and useContext Hooks

In React, we want to avoid the following problem of creating multiple props to pass data down two or more levels from a parent component

2. Context API

Context provides a way to pass data through the component tree without 
having to pass props down manually at every level.

The new Context API is made up of these three parts:
1. React.createContext
2. Provider
3. Consumer

Using the above three pieces we can really do a lot now.
Let's take a quick look at how they can be used.

step 1: React.createContext
const MyContext = React.createContext(defaultValue);

step 2:
<MyContext.Provider value={/* some value */}>

step 3:
<MyContext.Consumer>
{value => /* render something based on the context value */}
</MyContext.Consumer>
******Parent******
import React from 'react';
import { render } from 'react-dom';

const theme = {
buttonColor: 'blue',
alignItems: 'right',
};

a) const ThemeContext = React.createContext(theme);

const App = () => (
<div>
<h1>My App</h1>
b) <ThemeContext.Provider value={theme}>
<Container />
</ThemeContext.Provider>
</div>
);

export default App
export {ThemeContext}

******child A ******
const Container = () => (
<div>
<AppButton />
</div>
);

******child B******

import React from 'react';
import { render } from 'react-dom';
import { ThemeContext } from './app'

const AppButton = () => (
c) <ThemeContext.Consumer>
{({ buttonColor, alignItems }) => (
<button style={{ background: buttonColor , textAlign: alignItems,
width:400 }}>App Button</button>
)}
</ThemeContext.Consumer>
);

------PROBLEM WITH NESTED CONSUMERS-------
Yoshita Jain - 11.5K subscribers
https://www.youtube.com/watch?v=Qe9uObzq76M&list=PLp18NAIKHWnvpLpioGs6ZAiMlpfx49KOz&index=12

1. WHEN WE GOT MULTIPLE ITEMS TO PASS - IT BECOMES MESSEY AND
NESTED(SEE ABOVE) THIS PROBLME IS CALLED AS CALLBACKHELL
SOLUTION - useContext.

Youtube: Yoshita Jain — 11.5K subscribers
https://www.youtube.com/watch?v=Qe9uObzq76M&list=PLp18NAIKHWnvpLpioGs6ZAiMlpfx49KOz&index=12

GitHub :https://github.com/Hansraj-singh-tomar/reactHooks/tree/master/src/component/useContext

/* React Context API helps us avoid creating multiple duplicate props. This pattern is also called props drilling.  */
/* PASSING props -> APP -> MAIN -> HEADER*/
function App() {
const [user] = React.useState({ name: "Fred" });
return (
<Main user={user} /> // First 'user' prop
);
}
const Main = ({ user }) => (
<>
{/* Second 'user' prop */}
<Header user={user} />
<div>Main app content...</div>
</>
);
const Header = ({ user }) => <header>Welcome, {user.name}!</header>;

Context API

is helpful for passing props down multiple levels of child components from a parent component

/*  Here is the previous example rewritten with Context.
First we create context, where we can pass in default values. We call this 'UserContext' because we're passing down user data. */
const UserContext = React.createContext(); //A
const UserContextCity = React.createContext();

---PARENT1---
function App() {
const [user] = React.useState({ name: "Fred" });
return (
/* We wrap the parent component with the Provider property
We pass data down the component tree on the value prop */
<UserContext.Provider value={user}> //B.
<UserContextCity.Provider city={"London"}>
<CHILD1 />
<UserContextCity.Provider>
</UserContext.Provider>
);
}
export {UserContext, UserContextCity}
---CHILD1---
const CHILD1 = () => (
<>
<CHILD2 />
<div>Main app content</div>
</>
);
---CHILD2---
import { UserContext, UserContextCity } form './app'

const CHILD2 = () => (
<UserContext.Consumer>
<UserContext.Consumer>
{(user, city) => {
<header>Welcome, {user.name}! and city is {city}</header>
}}
<UserContext.Consumer>
</UserContext.Consumer>
);
note : we have to use function { (prop1) =>{ .....}}.

useContext hook

remove the problem of Context API (CALLBACKHELL)

useContext hook
Create -> Provider -> useContext
App->ChildA->ChildB->ChildC
import { UserContext, UserContextCity } form './app'

function Child2() {
/* remove the Consumer tags */
const user = React.useContext(UserContext);
const city = React.useContext(UserContextCity);
return (
<header>Welcome, {user.name}! and city is {city} </header>
)
}

Reducers and useReducer

Reducers are simple, predictable (pure) functions that take a previous state object and an action object and return a new state object.

/* This reducer manages user state in our app: */
function userReducer(state, action) {
/* Reducers often use a switch statement to update state in one way or another based on the action's type property */
switch (action.type) {
/* If action.type has the string 'LOGIN' on it, we get data from the payload object on action */
case "LOGIN":
return {
username: action.payload.username,
email: action.payload.email,
isAuth: true,
};
case "SIGNOUT":
return {
username: "",
isAuth: false,
};
default:
/* If no case matches the action received, return the previous state */
return state;
}
}

Reducers are a powerful pattern for managing state that is used in the popular state management library Redux (commonly used with React)

Reducers can be used in React with the useReducer hook in order to manage state across our app, as compared to useState (which is for local component state)

useReducer can be paired with useContext to manage data and pass it around components easily

useReducer + useContext can be an entire state management system for our apps

const initialState = { username: "", isAuth: false };
function reducer(state, action) {
switch (action.type) {
case "LOGIN":
return { username: action.payload.username, isAuth: true };
case "SIGNOUT":
// could also spread in initialState here
return { username: "", isAuth: false };
default:
return state;
}
}
function App() {
// useReducer requires a reducer function & initialState
const [state, dispatch] = useReducer(reducer, initialState);
// we get the current result of the reducer on 'state'
// we use dispatch to 'dispatch' actions, to run our reducer
// with the data it needs (the action object)

function handleLogin() {
dispatch({ type: "LOGIN", payload: { username: "Ted" } });
}

function handleSignout() {
dispatch({ type: "SIGNOUT" });
}

return (
<>
Current user: {state.username}, isAuthenticated: {state.isAuth}
<button onClick={handleLogin}>Login</button>
<button onClick={handleSignout}>Signout</button>
</>
);
}

Writing custom hooks

Hooks were created to easily reuse behavior between components, similar to how components were created to reuse structure across our application

Hooks enable us to add custom functionality to our apps that suit our needs and can be combined with all the existing hooks that we’ve covered

Hooks can also be included in third-party libraries for the sake of all React developers. There are many great React libraries that provide custom hooks such as @apollo/client, react-query, swr and more.

/* Here is a custom React hook called useWindowSize that I wrote in order to calculate the window size (width and height) of any component it is used in */
import React from "react";
export default function useWindowSize() {
const isSSR = typeof window !== "undefined";
const [windowSize, setWindowSize] = React.useState({
width: isSSR ? 1200 : window.innerWidth,
height: isSSR ? 800 : window.innerHeight,
});
function changeWindowSize() {
setWindowSize({ width: window.innerWidth, height: window.innerHeight });
}
React.useEffect(() => {
window.addEventListener("resize", changeWindowSize);
return () => {
window.removeEventListener("resize", changeWindowSize);
};
}, []);
return windowSize;
}
/* To use the hook, we just need to import it where we need, call it, and use the width wherever we want to hide or show certain elements, such as in a Header component. */
// components/Header.js
import React from "react";
import useWindowSize from "../utils/useWindowSize";
function Header() {
const { width } = useWindowSize();
return (
<div>
{/* visible only when window greater than 500px */}
{width > 500 && <>Greater than 500px!</>}
{/* visible at any window size */}
<p>I'm always visible</p>
</div>
);
}

Rules of hooks

There are two essential rules of using React hooks that we cannot violate for them to work properly:

Hooks can only be used within function components (not plain JavaScript functions or class components)

Hooks can only be called at the top of components (they cannot be in conditionals, loops, or nested functions)

React native Testing

Testing tools and environment

However, while the tooling and the use of the test suites are very similar, the testing environment and infrastructure have to be set up in a slightly different way. This is essentially because React apps are designed to work with the DOM inside a browser whereas mobile apps don’t target this data structure for rendering (they target actual ‘native’ modules that are on the mobile system instead).

Using Jest

Jest is a library used for testing JavaScript apps.

I wanted to use Jest for several reasons:

Firstly, it was created and is actively maintained by Facebook for their own React Native apps.

Secondly, it comes pre-packaged with the version of React Native I was working with (created using react-native).

Thirdly, Jest is a ‘comprehensive’ testing framework and contains the whole suite of testing tools I needed. For example, Jest comes with a library to check assertions, a test runner to actually run tests and tools to check code coverage. With other solutions, one has to choose and assemble individual components of a testing suite.

Using Jest + Enzyme

I wanted to combine Jest and Enzyme. There are lots of slightly confusing comments on the web that compare ‘Jest versus Enzyme’. This is a bit misleading. While Jest is a testing framework you can think of Enzyme as a library that makes it easier to select and query elements inside of an emulated DOM. So it is often used alongside Jest to make writing the logic of tests cleaner and easier to read.

Still confused? It’s similar to how jQuery introduced a concise and clear syntax for querying and selecting elements in the DOM, whereas the syntax using vanilla JavaScript was (at least back when jQuery was first introduced) not as clear and easy to use. And people don’t often compare ‘jQuery versus JavaScript’, unless they are comparing a particular way that the two approaches use to query and modify elements of the DOM.

Note: you can use Jest without Enzyme (I believe Facebook does this) but Enzyme makes your tests a bit easier to create and read. From my perspective, combining Enzyme with Jest is about convenience.

Setting up Jest + Enzyme

I had to jump through some hoops to successfully setup Jest and Enzyme in my React Native environment.

Jest now comes included with React Native apps created using the ‘react-native’ tool. So I could use Jest out of the box. Wonderful!

But I ran into some problems trying to combine Enzyme with React Native using their documentation. I never quite got to the bottom of what was the underlying problem, but I kept getting ‘modules not found’ errors like this one here.

A solution

In the end I used a solution that essentially abstracts away some of the setup into a pre-packaged environment using the jest-enzyme library and then made sure the jest ‘presets’ was set to ‘react-native’ in my package.json.

I followed the instructions to install these libraries:

npm install jest-environment-enzyme jest-enzyme enzyme-adapter-react-16 --save-dev

Errors when I tried to run my tests also directed me to explicitly install these myself too:

npm install --save-dev react-dom enzyme

Here is what I had to manually add to package.json:

// package.json before with react-native init{
...
"jest": {
"presets": ["react-native"],
}
...
}// package.json after my manual changes:{
..."jest": {
"presets": ["react-native"], // not clear in documentation!
"setupTestFrameworkScriptFile": "jest-enzyme",
"testEnvironment": "enzyme",
"testEnvironmentOptions": {
"enzymeAdapter": "react16"
}
}
...
}

You can see the repo here.

Using the jest-enzyme library in this way worked easily for me and it also meant that I had a slightly cleaner setup. This is because the other approach (that I couldn’t get to work, following the Enzyme documentation) would have meant I also had to set up and maintain a separate ‘jest config’ script.

Fetching Data

1. Using fetch

2. Using Axios

npm install axios

3. Using async/await syntax

In ES7, it became possible to resolve promises using the async / await syntax.

The benefit of this is that it enables us to remove our .then(), .catch(), and .finally() callbacks and simply get back our asynchronously resolved data as if we were writing synchronous code without promises altogether.

4. Using a Custom React Hook (useFetch)

Over time, you may realize that it gets a bit tedious and time-consuming to keep writing the useEffect hook with all of its boilerplate within every component in which you want to fetch data.

To cut down on our reused code, we can use a custom hook as a special abstraction, which we can write ourselves get from a third party library (like we are here, using the library react-fetch-hook).

5. Using the library React Query

Using For the requests below, our query for our random user data is identified by the string ‘random-user’ (provided as the first argument to useQuery).

custom hooks is a great approach to writing much more concise HTTP requests to get our data and all of its related state, but a library that really takes data fetching with hooks to the next level is React Query.

Summary

Writing business logic inside of Jest+Enzyme tests for React Native seems to be exactly the same as writing tests for React using Jest+Enzyme. This means the examples and documentation online for React unit testing are easily transferrable, which is really useful. This is a great step towards the vision of web developers being able to easily transfer their skills to create cross-platform mobile apps.

However, for the ease-of-use in the ‘test writing’ phase, I paid the price when setting up the infrastructure and environment so that the various tools were compatible with my React Native ecosystem.

In addition, from coming across Github issues in this area, it seems like there are lots of small instabilities between React Native versions that makes it really hard to find out what is the underlying cause of an infrastructure problem like the ones I described above. But I suppose we can’t have flexibility in such a fast-moving space as this without some challenges.

Here is the repo with my jest-enzyme setup with a few example tests.

I hope you found this interesting and useful! Please feel free to add any questions or comments below.

— — — — — — — — — — — — — — — — — — — — — — — — — — — -

The React TypeScript Cheatsheet — How To Set Up Types on Hooks

TypeScript lets you type-check your code in order to make it more robust and understandable.

In this guide, I will show you how to set up TypeScript types on React hooks (useState, useContext, useCallback, and so on).

Set types on useState

The useState hook allows you to manage state in your React app. It's the equivalent of this.state in a Class component.

import * as React from "react";export const App: React.FC = () => {
const [counter, setCounter] = React.useState<number>(0)

return (
<div className="App">
<h1>Result: { counter }</h1>
<button onClick={() => setCounter(counter + 1)}>+</button>
<button onClick={() => setCounter(counter - 1)}>-</button>
</div>
);
}

To set types on the useState hook, you need to pass into <> the type of the state. You can also use a union type like this <number | null> if you don't have an initial state.

Set types on useRef (typescript)

The useRef hook returns a mutable ref object that allows you to access DOM elements.

import * as React from "react";export const App: React.FC = () => {
const myRef = React.useRef<HTMLElement | null>(null)
return (
<main className="App" ref={myRef}>
<h1>My title</h1>
</main>
);
}

As you can see, the way useRef receives types is the same as the useState hook. You just have to pass it into the <>. And, if you have multiple type annotations, just use union type as I do here.

UseRef (javascript)

Refs and useRef
Refs are a special attribute that are available on all React components. They allow us to create a reference to a given element / component when the component mounts
useRef allows us to easily use React refs
We call useRef (at the top of a component) and attach the returned value to the element’s ref attribute to refer to it
Once we create a reference, we use the current property to modify (mutate) the element’s properties or can call any available methods on that element (like .focus() to focus an input)
function App() {
const [query, setQuery] = React.useState("react hooks");
/* We can pass useRef a default value.
We don't need it here, so we pass in null to reference an empty object
*/
const searchInput = useRef(null);
function handleClearSearch() {
/*
.current references the input element upon mount
useRef can store basically any value in its .current property
*/
searchInput.current.value = "";
searchInput.current.focus();
}
return (
<form>
<input
type="text"
onChange={(event) => setQuery(event.target.value)}
ref={searchInput}
/>
<button type="submit">Search</button>
<button type="button" onClick={handleClearSearch}>
Clear
</button>
</form>
);
}
--useRef
import React, { useRef } from 'react';
const UseReference = () => {
const textAreaEl = useRef(null);
const handleBtnClick = () => {
textAreaEl.current.value =
"The is the story of your life. You are an human being, and you're on a website about React Hooks";
textAreaEl.current.focus();
};
return (
<section style={{ textAlign: "center" }}>
<div>
<button onClick={handleBtnClick}>Focus and Populate Text Field</button>
UseReference
</div>
<label
htmlFor="story"
// style={{
// display: "block",
// background: "olive",
// margin: "1em",
// padding: "1em"
// }}
>
The input box below will be focused and populated with some text
(imperatively) upon clicking the button above.
</label>
<textarea ref={textAreaEl} id="story" rows="5" cols="33" />
</section>
);
};
export default UseReference;

Forwarding Refs

Ref forwarding is a technique for automatically passing a ref through a component to one of its children. Ex : used in reusable component libraries

Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.

To understand this first learn React.useRef and React.createRef.

React.useRef is used in the function component and React.createRef is used in the class component.

Both help to modify the DOM elements. like color change text change, value change. Onclick on button focus/hide the component.

Eaxmple of React.useRef Funtion 
const AppuseRef = (props) => {

const inputRef = React.useRef(null); //1
React.useEffect(() => {
console.log(inputRef.current);
inputRef.current.focus(); //3
inputRef.current.placeholder = 'Testing '; //4
}, []);

return (
<form>
<input type="text" placeholder="Enter Name" name="name" />
<br/>
<input type="text" name="name" ref={inputRef} /><br/> //2
___________________________________________
Example of class
class App extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef(null); //1
}
componentDidMount() {
console.log(this.inputRef.current); //3
this.inputRef.current.focus();
}
render() {
return (
<form>
<input
type="text"
placeholder="Enter Name..."
name="name"
ref={this.inputRef} //2
// or ref = {e => this.inputRef.current = e}
/>
</form>
);
}
}

----forwordRef()
Fundamentally, JSX just provides syntactic sugar for the
React.createElement(component, props, ...children) function. The JSX code:
NOTE : OnClick of button on the parent component you need to change
the value of the child input then we use the forwordRef()

Set types on useContext

useContext is a hook that allows you to access and consume a given Context in a React app.

import * as React from "react";interface IArticle {
id: number
title: string
}
const ArticleContext = React.createContext<IArticle[] | []>([]);const ArticleProvider: React.FC<React.ReactNode> = ({ children }) => {
const [articles, setArticles] = React.useState<IArticle[] | []>([
{ id: 1, title: "post 1" },
{ id: 2, title: "post 2" }
]);
return (
<ArticleContext.Provider value={{ articles }}>
{children}
</ArticleContext.Provider>
);
}
const ShowArticles: React.FC = () => {
const { articles } = React.useContext<IArticle[]>(ArticleContext);
return (
<div>
{articles.map((article: IArticle) => (
<p key={article.id}>{article.title}</p>
))}
</div>
);
};
export const App: React.FC = () => {
return (
<ArticleProvider>
<h1>My title</h1>
<ShowArticles />
</ArticleProvider>
);
}

Here, we start by creating the IArticle interface that is the type of our context.
Next, we use it on the createContext() method to create a new context, and then initialize it with []. You can also use null as an initial state if you want.

With that in place, we can now handle the state of the context and set the type on useContext in order to expect an array of type IArticle as a value.

Set types on useReducer

The useReducer hook helps you manage more complex states. It's an alternative to useState - but keep in mind that they are different.

import * as React from "react";enum ActionType {
INCREMENT_COUNTER = "INCREMENT_COUNTER",
DECREMENT_COUNTER = "DECREMENT_COUNTER"
}
interface IReducer {
type: ActionType;
count: number;
}
interface ICounter {
result: number;
}
const initialState: ICounter = {
result: 0
};
const countValue: number = 1;const reducer: React.Reducer<ICounter, IReducer> = (state, action) => {
switch (action.type) {
case ActionType.INCREMENT_COUNTER:
return { result: state.result + action.count };
case ActionType.DECREMENT_COUNTER:
return { result: state.result - action.count };
default:
return state;
}
};
export default function App() {
const [state, dispatch] = React.useReducer<React.Reducer<ICounter, IReducer>>(
reducer,
initialState
);
return (
<div className="App">
<h1>Result: {state.result}</h1>
<button
onClick={() =>
dispatch({ type: ActionType.INCREMENT_COUNTER, count: countValue })
}> +
</button>
<button
onClick={() =>
dispatch({ type: ActionType.DECREMENT_COUNTER, count: countValue })
}> -
</button>
</div>
);
}

Here, we start by declaring the action types that allow handling the counter. Next, we set two types for the reducer function and the counter state, respectively.

The reducer expects a state of type ICounter and an action of type IReducer. With that, the counter can now be handled.

The useReducer hook receives the reducer function and an initial state as arguments and returns two elements: the state of the counter and the dispatch action.

To set the type for the values returned by ueReducer, just pass into the <> the type of your data.

With that in place, the counter can now be incremented or decremented through useReducer.

Set types on useMemo

The useMemo hook allows you to memoize the output of a given function. It returns a memoized value.

const memoizedValue = React.useMemo<string>(() => {
computeExpensiveValue(a, b)
}, [a, b])

To set types on useMemo, just pass into the <> the type of data you want to memoize. Here, the hook expects a string as a returned value.

Set types on useCallback

The useCallback hook allows you to memoize a function to prevent unnecessary re-renders. It returns a memoized callback.

type CallbackType = (...args: string[]) => voidconst memoizedCallback = React.useCallback<CallbackType>(() => {
doSomething(a, b);
}, [a, b]);

Here, we declare the CallbackType type that is using as type on the callback we want to memoize.

It expects to receive parameters of type string and should return a value of type void.

Next, we set that type on useCallback - and if you pass a wrong type to the callback or the array of dependencies, TypeScript will yell at you.

You can find other great content like this on my blog or follow me on Twitter to get notified.

Thanks for reading.

— — — — — — — — — — —

Front-end-Developer-Interview-Questions

Table of Contents
1. General Questions
2. HTML Questions
3. CSS Questions
4. JS Questions
5. Accessibility Questions (external link)
6. Testing Questions
7. Performance Questions
8. Network Questions
9. Coding Questions
10. Fun Questions

https://dev.to/nabendu82/interview-preparation-whiteboard-take-home-and-skype-5147

Coding Practice

· Coderbyte

· Hackerrank

MORE…Coding Interview Questions

· Clearing Your Front End Job Interview — JavaScript

Interview-webdev Series' Articles (LINK ABOVE)
Back to Nabendu 's Series
Interview Preparation - Basic JavaScript-1
Interview Preparation - Basic JavaScript-2
Interview Preparation - Basic JavaScript-3
Interview Preparation - Basic JavaScript-4
Interview Preparation - ES6–1
Interview Preparation - ES6 questions-2
Interview Preparation - React & Redux-1
Interview Preparation - React & Redux-2
Interview Preparation - React & Redux-3
Interview Preparation - Object Oriented JavaScript-1
Interview Preparation - Object Oriented JavaScript-2
Interview Preparation - Algorithm Running Time
Interview Preparation - CSS Questions-1
Interview Preparation - CSS Questions-2
Interview Preparation - Tricky Questions-1
Interview Preparation - Tricky Questions-2
Interview Preparation - Whiteboard, Take Home and Skype
link
https://dev.to/emmabostian/decoding-the-front-end-interview-process-14dl

Course Curriculum

---

Course Curriculum
1. Introduction
2. Preview
3. Course Introduction (6:56)
4. Breaking Down the Interview Process The Big Picture (3:40)
5. Preparing Your Resume (6:36)
6. Recruiter Call (2:55)
7. Initial Screening Call (5:34)
8. Coding Project (3:12)
9. Onsite Interview (5:53)
10. Job Offer and Salary Negotiation (2:36)
11.JavaScript Section Overview -
12. JavaScript (3:00)
13. Variable Declarations - var vs let vs const (9:25)
14. Variable Declarations Exercise & Solution (3:29)
15. Understanding Scope (10:08)
16. Closures (10:16)
17. Closures Exercise & Solution (8:12)
18. Function Currying (7:57)
19. this Keyword (11:54)
20. this Keyworkd Exercise & Solution (5:18)
21. Arrow Functions (5:14)
22. Arrow Functions Exercise & Solution (1:35)
23. Function Currying Exercise and Solution (6:33)
24. Prototype (11:09)
25. More on Prototype (5:33)
26. Prototypal Inheritance (14:27)
27. ES6 class Keyword (4:06)
28. ES6 class Keyword Exercise & Solution (5:05)
29. Map (6:37)
30. Set (3:30)
31. Iterables and Iterators (19:51)
32. Iterables and Iterators Exercise & Solution (7:34)
33. Generators (10:16)
34. Generators Exercise & Solution (3:47)
35. Asynchronous JavaScript (5:47)
36. Timeouts and Intervals (7:38)
37. Timeouts and Intervals Exercise & Solution (7:46)
38. Callbacks (7:30)
39. Promises (Part 1) (15:52)
40. Promises (Part 2) (6:32)
41. async await (10:40)
42. async await Exercise and Solution (1:26)
43. Event Loop - Synchronous Code (7:12)
44. Preview Event Loop - setTimeout (8:47)
45. Event Loop - Promise (7:52)
46. Event Loop - setTimeout with Promise (8:24)
47. Suggested Learning (2:05)
48. Problem Solving Section Overview (2:04)
49. Sum of Numbers
50. Factorial of a Number
51. Fibonacci Sequence
52. Prime Numbers
53. Palindrome Anagram
54. Reverse Words
55. Remove Vowels from a String Palindromic
56. Substrings Array of Fullnames
57. Longest Word in a String
58. Array and Index Union Intersection
59. Difference Flatten Array
60. Duplicate Elements
61. Non Repeating Words Longest
62. Palindrome
63. Longest Substring
64. Group Anagrams
65. Miscellaneous Section Overview (1:29) HTML (13:05) CSS (19:06) React and Redux (9:08) Tooling (2:25)ping Up (1:43)

---

There's a plethora of resources out there that teach web development, but how do you know which ones are good? Here's a list of some of the awesome resources out there that share valuable web development knowledge.

I hope you have found this list useful. If there’s anything I’ve missed, be sure to let me know in the comments.

Interview question
Advanced JavaScript Practices
Object Oriented Programming
Functional Programming
Scope and Execution Context
Inheritance + Prototype Chain
Latest features: ES6, ES7, ES8, ES9, ES10, ES2020
Closures
Asynchronous JavaScript + Event Loop
JavaScript Modules
`this` keyword
JavaScript Engine and Runtime
Error Handling
Stack Overflow
Memory Leaks
Composition vs Inheritance
Type Coersion
Pass By Reference vs Pass by Value
Higher Order Functions
IIFE
.call(), .apply(), .bind()
Interpreter/ Compiler/ JIT Compiler
Garbage Collection
Hoisting
JavaScript best practices
JavaScript
  1. JAVA SCRIPT INTERVIEW QUESTION
  2. What is memoization. Implement JS code for memoization.
  3. What is bind? Implement pollyfill for bind.
  4. Write polyfill for : map, reduce, filter, promise
  5. What are pure functions.
  6. What is the difference between a shim and a polyfill?
  7. What is IIFEs (Immediately Invoked Function Expressions)?
  8. What is Coercion in JavaScript?
  9. What is the definition of a Higher-Order Function?
  10. When would you use the bind function?
  11. What is Currying?
  12. Explain what is Hoisting in Javascript
  13. Explain the Prototype Design Pattern
  14. Can you give an example of a curry function and why this syntax offers an advantage?
  15. What is the difference between the await keyword and the yield keyword?
  16. Compare Async/Await and Generators usage to achive same functionality
  17. Is it possible to reset an ECMAScript 6 generator to its initial state?
  18. How to deep-freeze object in JavaScript?
  19. Is JavaScript a pass-by-reference or pass-by-value language?
  20. Is JavaScript a pass-by-reference or pass-by-value language?

React

  1. What is function composition? Write sample code for HOC and pass some dummy state/props from it.What is the purpose of super (props)?

Maxschwarmueller

Lession and github repo

https://github.com/academind/react-complete-guide-code/tree/01-getting-started

maxschwarzmueller 
What's in this course?
• A thorough introduction to React.js (What is it and why use it?)
• All the core basics: How React works, building components with
React & building UIs with React
• Components, props & dynamic data binding
• Working with user events and state to create interactive applicaundergo
• A (thorough) look behind the scenes to understand how React works under
the hood
• Detailed explanations on how to work with lists and conditional content
• React Hooks (in-depth)!
• Working with built-in Hooks and building custom Hooks
• How to debug React apps
• Styling React apps with "Styled Components" and "CSS Modules"
• Working with "Fragments" & "Portals"
• Dealing with side effects
• Class-based components and functional components
• Sending Http requests & handling transitional states + responses
• Handling forms and user input (incl. validation)
• Redux & Redux Toolkit
• Routing with React Router
• An in-depth introduction into Next.js
• Deploying React Apps
• Implementing Authentication
• Unit Tests
• Combining React with TypeScript
• Adding Animations
• Tons of examples and demo projects so that you can apply all the things
you learned in real projects
• And so much more - check out the full curriculum on this page!

https://github.com/academind/react-complete-guide-code/commits/06-styling
/code/05-styled-components-dynamic-props/src

Experience in communicating with distributed/multinational teams.
Hands on experience in writing unit, integration and automation tests on all layers of the UI, including experience of Jest
and Playwright
Experience on the SOLID principles.
Knowledge of modern authorization mechanisms (Auth0 preferred), such as JSON Web Token.
Solid understanding of UI &amp; backend performance, accessibility, internalization, and localization
Experience in JavaScript, HTML and CSS.
Hands-on experience with designing and implementing reusable components.
Building continuous integration/deployment pipelines with robust testing and deployment schedules.
Good in Computer Science fundamentals — data structures, algorithm design, problem solving and complexity analysis

Unlisted

--

--

Devesh Kr Sri

Full Stack Developer with over 15 years of experince