Just got a bit confused about the lifecycle in react.
Here's my understanding...
The render() always run first, right? If so...
It implies that a setState() inside useEffect() only runs after the initial render(), correct?
Question:
When the above happens, does the entire component re-render?So that would be a second time the component renders just to load a state.
Wouldn't that be a performance issue?
On every state change render is called again but not whole component renders again.
React keeps Two DOM Tree Objects in memory:
Virtual DOM
Real DOM
React have a very intelligent and powerful diffing algorithm which calculates difference between previous DOM state and Next DOM state called Reconciliation process.
Only those sub elements which have changed would be re-rendered.Keys help React identify which items have changed, are added, or are removed.Keys should added to list or array elements , to give those elements a stable identity
For example, you want to delete <input key="i42"/> element from your list so on left side Its Actual DOM Tree Object and on Right side its Virtual DOM tree object. React calculates difference between two and only the difference will be Recreated Intelligently.
https://reactjs.org/docs/lists-and-keys.html
https://reactjs.org/docs/reconciliation.html#the-diffing-algorithm
So the thing about React is that there are two DOMs -- one is the actual DOM, and the other is the virtual DOM. Every time there is a state change, the virtual DOM re-renders. React then compares the changes to the virtual DOM vs changes to the real DOM, and only updates the real DOM with what has actually changed.
Re-rendering the virtual DOM is not a performance issue as it's super quick.
There's a cool article you can read about this
Related
I have a large number of elements being rendered by a common parent. When the user takes an action, a few of the elements should be removed, and a few additional elements should be appended. Doing this the 'React way,' the parent has an array that owns the state of all the children elements. On user on click, the parent immutably modifies the array and voila...new elements in the DOM. The problem is that it's often sluggish due to having to compare every element on the page, even with element keys and memoization. I have been fighting with React's diffing algorithm to make this work efficiently. Ideally, this parent component would be responsible solely for appending new children...once they're bootstrapped, they would control their own state.
I've just read about Portals, and am trying to understand whether ReactDOM. createPortal(<Child />, document.getElementById('myFavoriteDiv')) will allow this append-only behavior without altering any of the previously-rendered children. The non-declarative way of doing this I think would be appendChild, but I think that's frowned upon. If this doesn't work like that, what alternatives would you suggest?
This always puzzled me. If I said "Thank you React, your state hooks are awesome, but I'm just gonna do my direct dom manipulation here", would react still do the virtual dom comparison in order to update only that specific item? would I still benefit from the virtual dom 'situation'?
Is there any difference between using react to directly manipulate dom without states, and using a standard HTML file with imported vanilla js code?
For clarity, here's an example,
Let's say I have function printHellol() triggered by a button 'click' in my JSX. The function targets the ID of an element and changes the text content.
I couldn't find the answer anywhere. Thanks!
Anything that his held in state becomes part of an object that react renders as a detached element from the dom. It's in essence creating a separate environment for all states. Anything that is used outside of state can be considered to be part of the direct dom object, causing the page to be rerendered when updates occur. In other words you would need to use the react specific state if you want to access the virtual dom specific environment.
React Lifecycle
Can someone explain the order of these operations in the react lifecycle? The picture shows events occurring both vertically and horizontally but I don't understand the order of these events. For example, "First is the mounting phase where first the constructor is called then render is called etc...". In other words, how can one understand this diagram. Is it, for each horizontal phase ie. Mounting, Updating, and Unmounting we evaluate each vertical operation ie, constructor(), render(), ...componentDidMount()?
I believe you have the right idea - for each vertical phase, you evaluate it going down. When a component mounts, it is created (via the constructor call), then it renders, then calls componentDidMount. The trick here is that the same render method is called both during mounting (after construction) and during updating (after new props, setState, or forceUpdate). That's why render is a horizontal bar - it's literally the same function that's called in both vertical flows, so representing it as disjoint processes in each vertical segment could be misleadinng. Does that make sense?
In simple term, though I am more of functional developer/hook developer than class syntasism(this is just my own made grammarπ) so my answer might not give you the best or all. To go straight to the point, below is the order of react-lifecycle(the whole life sperm of a component or UI).
render => componentWillMount => componentDidMount => componentWillUpdate =>
componentDidUpdate => componentWillUnmount
render: for class components is the first life-cycle method that ships your UI-structure to the virtual DOM when the Ui is first created(take note: when the Ui is first created it gets executed and when other life-cycles get executed, they also depend on this lifecycle because without it, your Ui in a class component won't show. This makes this lifecyle the only method that exists from first render until unmounted).
componentWillMount: hmmm, this life-cycle is been deprecated 2 years ago but to caught the long story short, you can do some synchronous event here with the mindset that the synchronous operation will be executed while the component is mounting(i call it aka alongSideLifeCycle). Mind you, does synchronous operation don't have to depend on the DOM to be set before carrying out the operation else, there will be some performance issue.
componentDidMount: hmmm, this lifecycle gets executed ones a component has been successfully mounted(but mind you, it works just the way a defer attribute works in HTML script tag,i.e its loads the operation/lifecycle to the component background and that makes the execution super fast and most times can't be noticed if you are not using some tracking devtools ). This lifecycle is the best place to carry out components-side-effects-operation aka effect(effect are things that can utter the current state, view or structure of an application e.g: async operation, DOM nodes update, DOM-API operations like timeouts, eventListeners).
componentWillUpdate: this lifecycle gets executed first anytime a component wants to update/ change anything (either it affects the UI visually or not).
componentDidUpdate: this is the best place to do some necessary clean up to avoid things like memory leak aka direct or indirect unnecessary recursion or re-occurency. e.g best place to do: removeEventLister, clearTimeout/clearInterval, any form of unsubscription.
the last one is componentWillUnMount: basically, a perfect place to the destroy the state to initialState of that component because literally, the component structure aka DOM_NODES has been technically destroyed so why keep the value-less state that its own existence depends on the existence of the destroyed component file but mind you, imperatively, that is automatically done by react-ecosystem and there is no need doing it declaratively!
Bonus point: in react, there is an algorithm called "diffing" and during componentDidUpdate, the react UI dont ship unchanges structures to the actual DOM tree again(never) but it executes the "diffing" algorithm which trys to check the current virtual DOM structure and create a new virtual DOM structure based on things that have changed, and then react do what we call "reconcialiation" which is the process of settling the Virtual-DOM changes with the real Browser DOM to know what to put into the real DOM.
This process of diffing, reconciliation and Virtual DOM made React the boss π¨πΏβπ» π¨πΏβπ» π¨πΏβπ» of UI libraries because it reduces redundant rendering thereby making the ui-mounting process super fast βοΈ βοΈ βοΈ
So hope that clarified you π
In our experience, thinking about how the UI should look at any given moment, rather than how to change it over time, eliminates a whole class of bugs.
From React Docs
From my understanding, this means that React only updates what's necessary, rather than destroying and re-constructing the entire DOM tree again. Am I wrong?
Can anyone please help me understand the quoted statement?
Thanks.
From my understanding, this means that React only updates what's necessary, rather than destroying and re-constructing the entire DOM tree again. Am I wrong?
If you want to know the short answer, I have to say it is true, React will update the necessary elements in DOM whenever it needed.
But if you want to know how it's done, and when React will update the DOM and its element I have to it is varying to different several things, like project architecture, using proper methods (proper hooks in functional component eg. useCallback, useMemo, and so on) and so on.
When it truly gets rerender then?
As far as I know, there are two ways React finds out when to rerender the DOM.
Passing elements to ReactDOM.render
Update a state
What is ReactDOM.render?
This will call the render() method from react-dom (Where we usually import it as ReactDOM) and it will render a React element into the DOM in the supplied container and return a reference to the component (or returns null for stateless components). Also if the React element was previously rendered into the container, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React element.
What does state mean?
The state object is where you store property values that belong to the component. So when you got a component and that component has their own specific variables where changing them should affect the DOM you should use it, then whenever state gets changes the component will be updated.
So what I even talk about project architecture and this stuff, when I didn't mention anything about it above?
Let's say we got a project with one parent component and 3 child component just like this:
Component 1
- |- Component 2
- - |- Component 3
- - - |- Component 4
So whenever you a state in Component 4 all of the DOM elements will be get rerendered, why then? Because Component 4 is a child of Component 3 and so on, so when the child state gets change it will force the parent to rerender then the whole DOM will rerender once per state change.
Final Note
So, at last, we should be always considered a good architecture and hierarchy for our project or when it necessarily use built-in methods like useMemo to avoid such a thing.
in react js in reander it create virtual DOM compare with browser DOM and update browser DOM. Rather than having virtual DOM why not to update directly in browser DOM.
Performance. Reading/writing to DOM is very expensive. It is much faster to calculate changes on JS data structure and then just do minimal amount of changes on real DOM. Except for some special cases you can avoid reading browser DOM alltogether thats why react is so fast.
Check this simple benchmark as you can see reading is not expensive. Writing is also not expensive but reading and writing is crazy expensive. (updateNode function does reading and writing)
Image is taken from this talk which I really recommend.
The DOM is made up of nodes that are rendered by your browser. As your application receives input from the user, it has to change certain nodes in order to show it's response (Ex- A button turning blue from red when the user clicks on it). Now, DOM is not good at doing anything smart. So, any time anything changes, it will re-render every node from scratch. This is a costly process.
React adds the brains to DOM by telling the DOM which node to render and which node to leave as it was. (Ex- Except the button, everything else in the UI should not change). This is done by storing the state of your DOM in JS in the form of nested objects (Forming a tree like strcuture). Changes to specific parts of this object will help React figure out which part of the DOM tree actually needs to be re-rendered. This is done using the concept of immutability which is very nicely explained in the ReactJS docs. So it basically diffs the new object with the old one and tells the DOM to make changes to specific nodes ONLY, thus improving performance by many folds.