What is Dom in React?Real/Browser DOM:DOM stands for 'Document Object Model'. It is a structured representation of HTML in the webpage or application. It represents the entire UI(User Interface) of the web application as the tree data structure. It is a structural representation of HTML elements of a web application in simple words. Whenever there is any change in the state of the application UI, DOM is updated and represents the change. The DOM is rendered and manipulated with every change for updating the application User Interface, which affects the performance and slows it down. Therefore, with many UI components and the complex structure of DOM, It will update in more expensive as it needs to be re-rendered with each change. The DOM is constituted as a tree data structure. It consists of the node for each UI element present in the web document. Updating the DOM:If we know some about JavaScript you may see people using the 'getElementById()' or 'getElementByClass()' method to modify the contents of DOM. Whenever there is any change that occurs in the state of your application, the DOM is updated to reflect the change in the UI. How Virtual DOM speeds things up:When any new things are added to the application, the virtual DOM is created, represented as a tree. Every element in the application is a node in the tree. Therefore, whenever there is a change in the position of an element, a new virtual DOM is created. The newer virtual DOM tree is compared with the latest, where the changes are noted. It finds the possible way to make these changes by the actual DOM. Then the updated elements would re-render on the page. How Virtual DOM Helps in React:Everything in React is observed as a component, a functional component, and a class component. A component has a state. Whenever we change something in the JSX file, to put it simply, whenever the state of the component is changed, the react updates its virtual DOM tree. React maintains two virtual DOMs every time. The first one contains the updated virtual DOM, and the other is a pre-updated version of the updated virtual DOM. It compares the pre-updated version of the updated virtual DOM and finds what was changed in the DOM, like which components will be changed. Although it may seem ineffective, the cost is no more, as updating the virtual DOM cannot take much time. When comparing the current virtual DOM tree with the previous one is known as 'defying'. Once React knows what has changed, it updates the objects in the actual DOM. React uses batch updates to update the actual DOM. It changes to the actual DOM are sent in batches rather than sending any updates for the single change into the component's state. Re-rendering the UI is the most expensive part, and React manages to do most efficiently by ensuring the Real DOM that receives the batch updates to re-render the UI. The process of converting the changes to the actual DOM is called reconciliation. It improves performance and is the main reason developers love react and its Virtual DOM. What is React's Virtual DOM?The concept of Virtual DOM comes to make the performance of Real DOM better and faster. Virtual DOM is a virtual symbol of the DOM. But the main difference is that every time, with each change, the virtual DOM gets updated instead of the actual DOM. For example, the real and virtual DOM is represented as a tree structure. Every element in the tree is a node. A node is added to the tree when a new item is added to the application UI. If the position of any elements changes, a new virtual DOM tree is created. The virtual DOM computes the minimum number of operations on the real DOM to make changes to the real DOM. It is efficient and performs better by reducing the cost and operation of re-rendering the whole real DOM. Now we have a normal understanding of Real and Virtual DOM. Let's look at how React works by using Virtual DOM.
In the image, the dark blue circles are the nodes that have been changed. The state of these components has changed. React computes the difference between the previous and current version of the virtual DOM tree, and the entire parent sub-tree is re-rendered to show the UI which is changed. The updated tree is batch updated (that updates to the real DOM are sent in batches instead of sending updates for each state change.) to the real DOM. To get deeper into this, we need to know about the React render () function. Then, we need to know about some of the important features of React. JSXJSX stands for JavaScript XML. It is a syntax extension of JS. Using JSX, we can write HTML structures in the file which contain JavaScript code. ComponentsComponents are independent and reusable of code. Every user interface in the React app is a component. A single application has many components. Components are of two types, class components and functional components. Class components are stateful because they use their "state" to change the user interface. Functional components are stateless components. They act like a JavaScript function that takes an arbitrary parameter called "props". React Hooks have been introduced to access states with functional components. Lifecycle MethodsLifecycle methods are important methods built-in to react, which operate on components through their duration in the DOM. Each component of React went by a lifecycle of events. The render() method is the maximum used lifecycle method. It is the only method within React class components. So, in each class, component render() is called. The render () method handles the component's render by the UI. The render () contains all the logic displayed on the screen. It can also have a null value if we don't want to show anything on display. Example is shown below: The example will show the JSX written in the render(). When a state or prop is updated within the component, render() will return a different tree of React elements. When writing the code in the console or the JavaScript file, these will happen:
Finally, traverse the tree on the screen display. So as we know that updating the DOM involves changing the content. It is more attached to it. Complex algorithms are involved in recalculating CSS and changing the layouts, which affect the performance. So, React has many ways of dealing with it, as it uses something known as virtual DOM. reactdomeThe react-dom package provides DOM-specific methods at the top level of the application to escape route out of the React model if needed. If you use ES5 with npm, you should also write: The react-dom package also provides modules specific to the client and server apps:
The react-dom package exports of these methods:
The react-dom methods are also exported:
Note: Both hydrate and render have been replaced with newer client methods.Browser SupportReact supports all modern browsers, and some polyfills are required for older versions. Note: We cannot support older browsers that do not support ES5 methods, Like, Internet Explorer. You can find that apps work in the latest browsers if polyfills like es5-shim and es5-sham that included in the page, but you're on your own if you take the path.ReferencecreatePortal() Creates Portal () Portal provides the way to read children into the DOM node, which exists outside the ranking of the DOM component. flushSync() Force React updates in the provided callback simultaneously. It ensures the DOM is updated immediately. Note:
Legacy Referencerender() Note: Render is replaced with creating Root in React. Render a React element into the DOM at the supplied container and repay a reference to the component.If a React element were previously rendered into any container, it would perform an update on it, and it is necessary to reflect the latest React element. It is executed when the component is rendered if the optional callback is provided. Note: Render () method controls the content of the container node when it passes by. Any existing DOM element is replaced. Render () does not alter the container's node (it can only modify the container's children). It might be possible to insert a component into an existing DOM node without overwriting the child elements. Render () currently back reference to the root instance of ReactComponent. However, its return value is inherited and can be avoided as, in some cases, future versions of React may generate components asynchronously. If you need a reference to the ReactComponent prototype, the best solution is to attach a recall reference to the element. Render () is used to hydrate a rendered container to the server is obsolete. Use hydrateRoot() in place of it. hydrate()hydrate is replaced with the hydrate Root. It is exactly as render() but is used for a container whose HTML content is rendered by ReactDOMServer. React will try to connect event listeners to the current markup. Note: React expects rendered content to be identical between the server and client. We can correct the content of the text, but we must treat the inconsistencies as errors and right them. In development mode, React warns of the inconsistency during hydration. There is no assurance that specific differences are corrected for discrepancies. It is important for performance reasons in most applications, and it will be too expensive to validate all flags. Suppose an element's attribute or text content inevitably differs between the server and the client (for example, the timestamp). In this case, we can silence the alert by adding suppressHydrationWarning = {true} to the element. If it's not a text element, it cannot try to patch it so that it may remain inconsistent until future updates. You can perform a two-pass render if we need to provide different on the server and client deliberately. Components left on the client can read state variables like this.state.isClient, where it will set to true in componentDidMount(). The initial render pass will do the same as the server, avoiding inconsistencies, but the additional pass will be made synchronously after hydration. Note: This approach will make the components slower since they do it twice, so use it carefully.Note:unmountComponentAtNode has been replaced with root.unmount() in React. It erases the mounted React component from the DOM and cleans its event handlers and state. If no component was mounted to the container, it can't do anything. Returns true if no component is mounted and false if there is no component to unmount. findDOMNode()Note: findDOMNode is an escape hatch used to access the underlying DOM node. This escape hatch is discouraged in most cases because it pierces the component abstraction. It has been deprecated in StrictMode.findDOMNode(component)If this component has been mounted to the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values from the DOM, such as form field values, and performing DOM measurements. In most cases, you can attach a reference to the DOM node and avoid using findDOMNode. When a component returns null or false, findDOMNode returns null. When a component is rendered to a string, findDOMNode returns a text DOM node containing that value. The component can return a fragment with multiple children in case findDOMNode has returned the DOM node corresponding to the first non-empty child. Note: findDOMNode only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that hasn't been mounted yet (such as calling findDOMNode() on render() on a component that hasn't been created yet), an exception will be thrown. findDOMNode cannot be used in function components. DOM elementsReact implements a browser-independent DOM system for the performance and with cross-browser compatibility. We take this opportunity to clean up some of the rough edges in the browser's DOM implementation. In React, all the DOM properties and attributes (including event handlers) must be camelcase. For example, the HTML tabindex attribute corresponds to the tab Index attribute in React. The exceptions are the aria-* and data-* attributes, which must be lowercase. For example, you can have an area tag as an area tag. Differences in AttributesSeveral attributes will work differently between React and HTML: checkedThe checked attribute is supported by components of a checkbox or radio of type <input>. It is useful for manufacturing controlled components. You can use this to determine whether the component is checked or not. DefaultChecked is the unchecked counterpart that determines the component is checked the first time it is mounted. classNameTo specify the CSS class, use the className attribute. It applies to all regular DOM and SVG elements like <div>, <a>, etc. If you use React with Web Components (uncommon), use the class attribute instead. dangerouslySetInnerHTMLDangerously SetInnerHTML is React's replacement for using innerHTML in the DOM browser. Configuring HTML code is risky because it is easy to expose the users to a cross-site scripting (XSS) attack. So we can set HTML directly from React, but you have to dangerously type SetInnerHTML and pass an object with the __html key to remember that it's dangerous. For example:React elements use htmlFor instead, Since for is a reserved word in JavaScript. onChangeThe onChange event behaves as expected; the event fires every time a form field is changed. We intentionally don't use the existing browser behavior because change is grand for its behavior and React relies on the event to handle user input in real-time. selectedIf you want to mark the <option> as selected, refer to that option's value in the <select>'s value instead. See "Select Tag" for detailed instructions. Note: In maximum cases, class names refer to classes defined in an external CSS style sheet. Styles are used in React apps to add calculated styles at render time. The style attribute accepts the JavaScript object with camel properties instead of a CSS string. It conforms DOM-style JavaScript properties, is more efficient, and avoids XSS security holes. For example: Note that: styles are not autoprefixed. To support older browsers, we need to supply style properties:Style keys are camel to correspond to accessing properties on DOM nodes from within JS. Provider prefixes MS begin with an uppercase letter. React will automatically add a "px" suffix to some inline number style properties. If we want to use units other than "px", specify the value as a string with the desired unit. for example: However, not all the style properties are converted to pixel strings. Suppress Editable Content AlertThere is a warning if an element to children is marked as content editable, as it will not work. The attribute suppresses the warning. Suppression WarningIf we use server-side React rendering, it is a warning when the server and client render with different content. However, it is hard to guarantee an exact match in rare cases. For example, timestamps are expected to differ at the server or the client. If you set the suppression warning to true, it will not warn about mismatches between attributes and content of the element. It only worked at one level depth and was meant to be used as an escape. valueThe value attribute is designed by the <input>, <select> and <textarea> components. You can use it to setting the value of the component. It is useful for manufacturing controlled components. defaultValue and equal to unchecked set the component's value when mounted serially. All supported HTML attributesAny custom and standard DOM attribute are supported. React has provided a JavaScript-centric API in the DOM. And React components often contain custom and DOM-related props, and then React uses the same CamelCase conventions as the DOM API: Next TopicUnit Testing in React |