Summary: Learning about Virtual DOM, Class and Functional Components.
Virtual DOM in React
- The Virtual DOM (VDOM) is an in-memory representation of the real DOM (Document Object Model). It is a lightweight copy of the actual DOM used by React to optimize and efficiently manage updates in a web application.
- When the state of a React component changes, the virtual DOM gets updated first instead of directly manipulating the real DOM.
- React uses the virtual DOM to minimize direct DOM manipulations, which can be slow, and to ensure smooth and performant updates.
Initial Rendering
- React renders the entire UI by creating a virtual DOM tree that mirrors the actual DOM.
- Each element in the virtual DOM is a JavaScript object, representing an element in the real DOM with properties like type (div, h1, etc.), attributes (class, id, etc.), and children (nested elements).
State/Prop Changes
- When the state or props of a component change, React re-renders the virtual DOM and creates a new virtual DOM tree that reflects the updated UI.
- React compares the newly created virtual DOM with the previous one using a process called reconciliation.
Reconciliation and Diffing Algorithm
- Diffing: React compares the new virtual DOM with the previous one using an optimized diffing algorithm. Instead of comparing every single node, React only compares nodes that have changed, making it fast.
- Minimal Updates: After diffing, React determines the minimal set of changes required and updates only the parts of the real DOM that are affected, reducing unnecessary re-rendering and improving performance.
DOM Patching
- Once React has figured out the changes, it batches these changes and updates the actual DOM in a single operation (also known as “DOM patching”).
- This approach ensures fewer direct manipulations of the DOM, which is beneficial because DOM operations are relatively expensive.
Performance Optimization
- Manipulating the real DOM can be slow because each change triggers reflows and repaints, which affect the entire page layout. The virtual DOM allows React to manage and minimize these costly operations.
- By updating only the specific parts of the DOM that need to change, React avoids re-rendering the entire DOM tree.
React Fiber
- In React 16, React Fiber was introduced, which revamped the reconciliation process.
- Fiber allows React to pause, split, and prioritize work to ensure that the UI remains responsive. It’s particularly beneficial for animations or interactions where immediate feedback is required.
Keys in React
- React uses keys to efficiently track elements in lists during reconciliation. If keys are provided, React can quickly determine which elements were added, changed, or removed.
- This helps optimize list re-renders by avoiding unnecessary DOM manipulations.
Components
Components are the building blocks used to define the UI and manage its behavior.
Class Components
Class components in React are ES6 classes that extend React.Component
and contain methods that manage state, lifecycle, and rendering logic. They are older and were the primary way to manage state and lifecycle before React introduced Hooks in version 16.8.
Class components must have a render()
method that returns JSX (the UI). They can use state and have access to lifecycle methods.
import React, { Component } from 'react';
class MyComponent extends Component {
// Initial state
state = {
count: 0,
};
// Lifecycle method: called when component mounts
componentDidMount() {
console.log('Component mounted');
}
// Method to update state
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
};
// Required render method to display JSX
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}
export default MyComponent;
Lifecycle Methods: Class components have access to various lifecycle methods.
componentDidMount()
: Runs after the component is mounted.componentDidUpdate()
: Runs after the component updates.componentWillUnmount()
: Runs just before the component unmounts.
Functional Components
Functional components are simpler than class components. They are JavaScript functions that return JSX. Initially, functional components were stateless and lifecycle-free, but with the introduction of React Hooks, they gained the ability to manage state and use lifecycle-like features.
Functional components do not have this
and do not extend React.Component
. They just take props
as an argument and return JSX. State and lifecycle can be managed using Hooks like useState
, useEffect
, etc.
import React, { useState, useEffect } from 'react';
const MyComponent = () => {
// Using useState Hook to manage state
const [count, setCount] = useState(0);
// Using useEffect Hook to mimic componentDidMount lifecycle
useEffect(() => {
console.log('Component mounted');
}, []); // Empty array means it runs only once on mount
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default MyComponent;
Hooks
- useState: Allows functional components to use state
const [state, setState] = useState(initialValue);
- useEffect: A replacement for lifecycle methods like
componentDidMount
,componentDidUpdate
, andcomponentWillUnmount
.
useEffect(() => {
// Side effect logic
return () => {
// Cleanup (like componentWillUnmount)
};
}, [dependencies]); // Only run when dependencies change
Leave a Reply