0% found this document useful (0 votes)
8 views

React Notes

It is react Notes Simpple

Uploaded by

Muhammad Naveed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

React Notes

It is react Notes Simpple

Uploaded by

Muhammad Naveed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

1.

/In Strict Mode the React Renders the componenets twice

2.
//The JSX is converted to Pure React by babel
JSX is cleaner then the Pure React
(i.e (JSX) return (
<footer>{new Date().toLocaleTimeString()} We're currently open</footer>
);
//(Pure React) return React.createElement("footer", null , "We're currently
open!"))

3.
///when writing inline stlye in react for styling componenet the first you should
enter js mode {} and then inside it you should make an object
that of the style

4.
When we import the file like css into our application then it is the webpack that
will take
care of taking the css styles out of the css file and injecting it into our
application

5.
Always treat state as immutable in react dont mutate it because it is a bad
practice so always use the setFunction
in state dont update the var directly
UseState re renders the component through that it updates the dom
State is the brain of react (means when the components is re rendered it keeps the
other componenets data in track )

6.
In forms we should write onsubmit (not on button on click (f handleSubmit)) in
form element because when there is text written or something is selected
in form by pressing enter it is submiited directly on the other hand on button we
should have to click on that button

7.-----------------------REACT BEHIND THE


SCENES----------------------------------------
when a component is called of each component(blueprint) one instance is created Now
when react calls the instances each instance with its jsx will produce
a bunch of react element funtion calls now again it will produce react element for
each componenet instance this react element will
be transformed to dom elements(HTML) and presents user interface on the screen

---How Components are displayed on the screen


By Updating the state somewhere in the application Render is Triggerred Now Comes
the render phase
Render Phase : React calls Component Functions And figures how Dom should be
updated (It does not update the dom in this phase it does it in commit phase)
Commit Phase : React Writes to the dom updating inserting and deleting elements now
the browser will notice that the dom is changed the browser will
Paint the screen now the browser step is not react but it simple the
final step of painting the browser

Render Phase: Two Situation in which the render is triggered


1:Initial Render of the application(First Time when the application is
started)
2:When State is updated in one or more componenet instances(Instance is
the physical manifestation of the component has its own prop
and states has a lifeCycle (can be born live or die) means if one
component is called three times three instances will be created)
The render process is triggered for the entire application(During
rander react will check for the whole application that what state will
change(Renders are not triggered automatically but scheduled for when
the js engine has some free time(time is in milliSeconds)we can not
notice that)

Render Phase Details:At the begining of the re rendering phase react will go
through the component tree and re render all the instances that triggeredd
the re render and react will render them this together will
create react elements which then will create the virtual dom
when the render happens on the components this will create React
Element tree which is called virtual dom

Virtual Dom : Tree of all react elements created from all instances in the
componenet Tree(it is a javascript object fast to create multiples)
When a component is rendered all of its childs components will be
rendered as well (example if the app component is
updated then it will re render the entire application this is
because that react dont know that this update will effect the
child or not(not the entire dom is updated but only the virtual
dom)) after this the virtual dom will reconciled(reconcilation + diff)

Reconsilation+difing:Deciding which dom elements should be deleted inserted or


updated in order to reflect the latest state changes Reconsil... is
processed by reconsiler(we can say that the reconsiler is the
engine of the react(reconsiler allows us to never touch
:the dom directly it tells react what the next snap of the dom
should be based on state(it is called fiber-reconsiler)))

Reconsiler(engine :During the initial render of the application fiber takes the
entire element tree (virtual DOm) based on it create another
of react) tree which is called fiber tree
Important characteristic of fiber is that work can be done
asynchronusly(Rendering process can be split into chunks , tasks can be
prioritized over others and work can be paused reused or thrown
away if not valid anymore)

Fiber Tree :Fiber tree is the internal tree that has a fiber for each
component instance and dom elements(button etc)
Fiber are not created on every re render(instead it is a mutable
data structure and is mutated in future reconsil.. steps)
And this makes the fiber the perfect place for keeping tracks of
things like the current Component state , props ,side effects
etc ***The Actuall state and props of any component instance that
we see on the screen are internally stored inside the fiber tree
Also known as unit of work because it keeps queue of work (in this
tree each first child has a link to its parent and all the
other children then have a link to their previous siblings this
structure is called linked list )
the virtual dom and fiber tree not only has the structure of the
components but the entire dom structure

After all this process when the fiber tree is updated the list of
dom updates will be created

List of DOM Updates:React writes to the dom insertion deletion and updates (list of
dom updates are flushed to the dom)

Commit phase :it is synchronus Dom is updated in one go it cant be


interrupted this is necessary that the dom never shows partial results
ensuring a consistent UI (is sync with state all the times)
After the commit phase is completed the workInProgress fiber tree
becomes the current tree for the next render cycle

Diffing uses Two fundamental assumptions which are as follows

Diffing :1)Same Position , Different element


When in same position different dom elements occur it will destroy
the old ones and make a new tree
And also Different React elements at same position will destroy the
old ones (which completely will change the state)

2)Same position ,Same element


Element will be kept (as well as child elements),including state
New Props / attributes are passed if they changed between renders
sometime this is not what we want... Then we can use the key prop

key Prop :By Using the key prop when each render happens then react will
see it as a different component therefore it will change the state
:and not keep the state the same

State Update :Renders are not triggered immediatley but scheduled for when
the js engine has some "free time"
Batched There is batchin of multiple setState calls in event handlers
setTimeouts and now every where else
Means in one function there are multiple setState calls then it
exectues one state for the all
setStates in parrallel (how ever the state is not updated directly
but is happened after the re render)

in the below example the first three will update only one because in
the state is not updated with the rendering process
but after the re rendering in first iteration likes 0 + 1 how ever
the state is not updated in rendering process
so in the other line again likes will be 0 + 1 which will plus only
one to the number

so we should use the last three state updates in which we sets a


call back function in this the state will be updated three
at once because the second one will take now the latest like 0 + 1
and then 1 + 1 and 2+1 which will result in three

when we returns a state based on the previous one we should set a


call back like this so it will execute fine

function handleTripleInc() {
// setLikes(likes + 1);
// setLikes(likes + 1);
// setLikes(likes + 1);

setLikes((likes) => likes + 1);


setLikes((likes) => likes + 1);
setLikes((likes) => likes + 1);
}

Event Propagation :Event Propagation has two phases Capturing phase and Bubbling
phase In capturing phase when event is fired on a button
And Delegation then the event object is created which moves through each
parent down the dom tree until it reaches the desired target
after then when it is reached the target then it bubbles up the tree
during bubbling phase the event is fired(used)
but when it is bubbled up if the same event is used by some other
element then it will also be fired over there
this some time causes unnecessary things are happening for that we
can pause the bubbling (through e.stopPropagation)
but this is not the good way(only use this if there is no other
solution)

:Event Delegation Through this bubbling it allows developers to


implement a common technique and useful
called event delegation
Through event delegation we handle events for mmultiple elements
centrally in one single parent element
(Means if we attach to each single button event it might create
1000 events which is bad for performance )
if one div contains one thousand buttons and on each when we attach
event then there will be 1000 events
which will slow the performance but by adding handler to parent we
can prevent that copies
now we can attach e.target to access the target

if you want to capture the event in the capturing phase then just
use onClickCapture but you will not need that
just to keep in mind

Now when we attach handler on the button then react will attach the
handler not to the button but to the root the div with classname
root react will attach one event hanler per event type and it does
during the root note of the fiber tree during the render phase
(if we have multiple onClick event handlers then react will bundle
them all together in a one big onClick handler to the root
node of the fiber tree)

**********The Render phase is commited by the react library (that is why we import
react) does not touch the dom it does not know where the render
Result will go
**********The Commit phase is commited by the library React Dom (that is why we
import ReactDom )
**********The Browser Paint is done by the browsers itself

--Never call a component directly in a component because then react will not see it
as a instance therefore then it can not manage its states
and its states will lives in the parent component in which it is called
**************************************SECTION 12
***********************************************************************************
*********

USE-EFFECT :As We can not use side effects in the render logic there are two ways
of using side effects which is event handler function
and UseEffect hook sometimes we can not use effect in the event handler
because we want the side effect to automatically happen after
the render happens.This effect takes the second argument as dependency
array which takes props and states
Now when the props changes the effect is executed and is same for state
and the componenet is re rendered
if we specify empty array in the dependency argument then it will
mount/render on the initial Render
if we specify nothing then every time the render happens then it will
be executed (Means will be connected with all props states
With every thing etc)

UseEffect is rendered after the render commit and browser paint because
if it contains a code that has long running process
if it will be executed before browser paint then it will take more time
to paint the browser there is a effect that is executed
before the browser is painted

Layout Effect : this is the effect that is executed before the browser paint but we
will not have need of this

USE-EFFECT :Function that we can return from an effect(optional)


CleanUp Runs on two ocasion
function Before the effect is executed again
After a component has unmounted
we use this when the effect keeps executed its self after the component
has unmounted destroyed so we will cleanup that function/effect

The below example is of cleanup func the return is the cleanup func
Now if we execute the below function then it will be log to the console
title we have said that it runs after the component has unmounted
then how it remember its title that is because of closure (the function
rembebers all the variables at the time and the place that the function
was created) you can also check the first situation by selecting one movie
and again another

useEffect(
function () {
if (!title) return;
document.title = `Movie | ${title}`;

return function () {
document.title = "usePopCorn";
console.log(`Clean up effec for movie ${title}`);
};
},
[title]
);

USE-EFFECT :when we do fetch request when we type someword in the searcbar then
the componenet is re rendered which makes on each alphabet a request
IN you can see in network tab (It has a minor issue which means that
when we search inception if the search of inc tookes long
FETCH then the other alphabets then the last will be our query seeted and
also it has another issue that many data will be downloaded)
which is bad for performance

There is a browser api called abort controller(no need of how it works


but just take it as a recipe)
steps to include it
1) const controller = new AbortController();

2) const res = await fetch(


`http://www.omdbapi.com/?apikey=${KEY}&s=${query}`,
{ signal: controller.signal }
);

3)now when the request is cancelled means if we type inception(as on


each alphabet the component is rendered which will cause fetch
now this will be cancelled by this api as the other alphabet is typed
so this cancel will produce error(produced by javascript))
for that you should write in catch block the following

catch (err) {
if (err.name !== "AbortError") {
setError(err.message);
}

Using Use Effect For keypress and also removing that event because if we not remove
it then many events will be attached to it which will cause it
slow down its performance (Means if we open 10 movies details then 10 same event
listeners will be attached to the document)

useEffect(
function () {
function callback(e) {
if (e.code === "Escape") {
onCloseMovie();
}
}

document.addEventListener("keydown", callback);
return function () {
document.removeEventListener("keydown", callback);
};
},
[onCloseMovie]
);

You might also like