React Basics II Flashcards
How does React work (DOM)?
React operates by creating an in-memory virtual DOM rather than directly manipulating the browser’s DOM. It performs necessary manipulations within this virtual representation before applying changes to the actual browser DOM.
Reconciliation
React Reconciliation refers to React’s process of comparing the current and previous states of the Virtual DOM and updating the DOM efficiently.
It makes the DOM updates faster in React. It updates the virtual DOM first and then uses the diffing algorithm to make efficient and optimized updates in the Real DOM.
How ReactJS Reconciliation Works
Reconciliation in React follows these key steps
- Render Phase:
React calls the render() method of a component to generate a new Virtual DOM representation.
This new Virtual DOM is compared with the previous Virtual DOM snapshot. - Diffing Algorithm:
React compares the old and new Virtual DOM trees to determine the differences.
Instead of re-rendering the entire UI, React updates only the changed nodes. - Commit Phase:
Once the differences are determined, React applies the updates to the real DOM in the most efficient way.
React batches updates and minimizes reflows and repaints for better performance.
Virtual DOM in React
The Virtual DOM (VDOM) is a lightweight, in-memory representation of the actual DOM elements.
It allows React to perform DOM updates more efficiently by updating only the necessary elements, avoiding full re-renders of the entire UI.
The Virtual DOM is a concept borrowed from the idea of “virtualization” in computing, where operations are performed on a virtual version of an object (like the DOM) before applying those changes to the actual object. This results in a more optimized and less resource-intensive approach.
How Virtual DOM Works
Initial Rendering: React creates an initial Virtual DOM tree when the components are first rendered. React then compares the Virtual DOM with the actual DOM and updates the actual DOM only where necessary.
State/Props Changes: When the state or props of a component change, React creates a new Virtual DOM tree. React then compares the new Virtual DOM with the previous one, determining what parts of the actual DOM need to be updated.
Efficient DOM Updates: React uses the diffing algorithm to identify the differences between the new and previous Virtual DOM trees, updating only the parts of the DOM that have changed.
Diffing Algorithm and Its Role in Reconciliation
The Diffing Algorithm plays a crucial role in the Reconciliation process. It is responsible for
Identifying Differences: The diffing algorithm identifies the differences between the old and new Virtual DOM trees by comparing each element.
Minimizing DOM Changes: The algorithm ensures that only the minimal number of changes are applied to the actual DOM.
Optimization: The diffing algorithm optimizes updates by reusing elements where possible and only making necessary changes.
Key Principles of Reconciliation
React’s Reconciliation is based on some important principles that help make the update process efficient
Component Identity: React uses a component’s identity (i.e., the component class or function) to decide whether the component should be re-rendered or not. If the component’s identity is unchanged, React can update the existing component’s state and render it efficiently.
Minimal DOM Manipulation: Reconciliation aims to minimize direct DOM manipulations.** By updating only the parts of the DOM that have changed**, React avoids the performance hit that comes with full re-rendering.
**Efficient Update Strategy: **React doesn’t re-render the entire component tree when a state or prop change occurs. Instead, it identifies and updates only the parts that need to be changed.
Virtual DOM: React uses a virtual representation of the actual DOM (the Virtual DOM), which helps in calculating the minimal number of changes to be made.
Benefits of Reconciliation
The Reconciliation process offers several key benefits for React applications:
Improved Performance: By minimizing unnecessary updates to the DOM and only making necessary changes, Reconciliation improves the overall performance of React applications, especially for dynamic UIs with frequent updates.
Efficient Rendering: The process ensures that React updates the UI with the least amount of work, avoiding redundant re-renders, which can be costly in terms of performance.
Predictable UI Updates: With Reconciliation, React ensures that updates happen in a predictable and controlled way, making the UI consistent with the underlying data model.
Optimizing Performance with Reconciliation and Diffing
React uses Reconciliation and the Diffing Algorithm to ensure high performance. Some strategies for optimizing performance include:
Use of shouldComponentUpdate(): This lifecycle method allows you to prevent unnecessary re-renders of class components by returning false if the component’s state or props haven’t changed.
React.memo for Functional Components: React.memo() helps in optimizing functional components by** preventing re-renders** when the props have not changed.
Lazy Loading: React allows lazy loading of components using React.lazy(), which helps in loading components only when they are needed.
One-Way Data Binding
React uses one-way data binding, meaning data flows in a single direction from parent components to child components via props. This provides better control over data and helps maintain predictable behavior.
State Management
React manages component state efficiently using the useState hook (for functional components) or this.state (for class components). State allows dynamic updates without reloading the page.
React Hooks
Hooks allow functional components to use state and lifecycle features without needing class components. Common hooks include:
useState: for managing local state.
useEffect: for handling side effects like API calls.
useContext: for global state management.
React Lifecycle
- Initialization
This is the stage where the component is constructed with the given Props and default state. This is done in the constructor of a Component Class.
- Mounting Phase
Constructor: The constructor method initializes the component. It’s where you set up initial state and bind event handlers.
render(): This method returns the JSX representation of the component. It’s called during initial rendering and subsequent updates.
componentDidMount(): After the component is inserted into the DOM, this method is invoked. Use it for side effects like data fetching or setting timers.
- Updating Phase
componentDidUpdate(prevProps, prevState): Called after the component updates due to new props or state changes. Handle side effects here.
shouldComponentUpdate(nextProps, nextState): Determines if the component should re-render. Optimize performance by customizing this method.
render(): Again, the render() method reflects changes in state or props during updates.
- Unmounting Phase
componentWillUnmount(): Invoked just before the component is removed from the DOM. Clean up resources (e.g., event listeners, timers).
2 types of export
Default Export and Import:
A default export allows you to export a single component or variable from a file. When importing a default export, you can give it any name you choose.
Named Export and Import:
Named exports allow you to export multiple components or variables from a single file. When importing a named export, you must use the exact name of the exported entity.
Can I use JSX without React?
JSX is specifically designed for React and requires React libraries to work.
What happens if I don’t use a key in lists?
React will warn about missing keys, and updates may behave unpredictably.
What are fragments in JSX?
Fragments (<> </>) let you group elements without adding an extra DOM node.
Functional Components
Functional components are simpler and preferred for most use cases. They are** JavaScript functions that return React elements. With the introduction of React Hooks, functional components can also manage state and lifecycle events**.
Stateless or Stateful: Can manage state using React Hooks.
Simpler Syntax: Ideal for small and reusable components.
Performance: Generally faster since they don’t require a ‘this’ keyword.
Class Components
Class components are ES6 classes that extend React.Component. They include additional features like state management and lifecycle methods.
State Management: State is managed using the **this.state **property.
Lifecycle Methods: Includes methods like componentDidMount, componentDidUpdate, etc.
Props in React Components
Props (short for properties) are read-only inputs passed from a parent component to a child component. They enable dynamic data flow and reusability.
Props are immutable.
They enable communication between components.
State in React Components
The state is a JavaScript object managed within a component, allowing it to maintain and update its own data over time. Unlike props, state is mutable and controlled entirely by the component.
State updates trigger re-renders.
Functional components use the useState hook to manage state.
Rendering a Component
Rendering a component refers to displaying it on the browser. React components can be rendered using the ReactDOM.render() method or by embedding them inside other components.
Ensure the component is imported before rendering.
The ReactDOM.render method is generally used in the root file.
What is the difference between props and state?
Props are immutable and passed from parent to child, while state is mutable and managed within the component.
Can I use state in functional components?
Yes, functional components use the useState hook to manage state.
When should I use class components?
Class components are mainly used when lifecycle methods or error boundaries are required.
How do I pass data between components?
Data is passed from parent to child using props. For sibling communication, a shared state or context can be used.
Ways to Implement Conditional Rendering in React
Using If/Else Statements (not inside JSX! multiple returns)
Using Ternary Operator
Using Logical AND (&&) Operator
Using Switch Case Statements
Conditional Rendering in Lists (Using .map())
Conditional Rendering with Component State
What is the difference between && and the ternary operator (? 🙂 in JSX?
&& is used when only one element should be conditionally rendered. On the other hand ? : is used when both “if” and “else” cases need to be handled.
Why is conditional rendering important?
It improves user experience by ensuring only relevant information is shown, reduces unnecessary rendering, and keeps the UI dynamic and responsive.
What is the best approach for complex conditions?
For complex conditions, using helper functions, switch-case statements, or breaking logic into separate components can improve readability and maintainability.
Can conditional rendering impact performance?
Yes, frequent re-renders due to inefficient conditional logic can impact performance. Using memoization (React.memo()), lazy loading (React.lazy()), and state optimizations can help.
How does conditional rendering differ from normal rendering?
Normal rendering statically displays UI elements, whereas conditional rendering dynamically updates UI elements based on conditions.
What is ReactJS PropTypes?
PropTypes is a tool in React that helps us check if the data (props) being passed to a component is of the correct type. The react components receive various types of props and PropTypes help make sure that the right kind of data (like a string, number, or object) is passed to your components.
Type Safety: When the wrong data type is passed in the component, prototypes help find the issues.
Better Debugging: During development, they give warning messages in the console, which makes it easier to find the bugs.
Improved Documentation: It acts as self-documentation for your components, showing the expected types of props.
Prevents Runtime Errors: We can avoid errors caused by unexpected data types during the execution of the application, by enforcing prop types.
Props types example
import React from ‘react’;
import PropTypes from ‘prop-types’;
const Greeting = ({ name, age }) => {
return (
<div>
<h1>Hello, {name}!</h1>
<p>You are {age} years old.</p>
</div>
);
};
Greeting.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
};
Greeting.defaultProps = {
age: 25,
};
export default Greeting;
What are PropTypes in React?
PropTypes are a way to validate the props passed to a React component, ensuring that they are the correct type.
Are PropTypes mandatory in React?
No, PropTypes are not mandatory in React. However, they are useful for debugging and ensuring data consistency during development.
Can I use PropTypes with TypeScript?
While TypeScript provides static type checking, PropTypes can still be used in a project alongside TypeScript, but they are often redundant in such cases.
Can I define default values for props?
Yes, you can define default values for props using defaultProps in React.
What happens if I pass the wrong type for a prop?
React will display a warning in the console during development if you pass the wrong type for a prop.