Rendering a Component

08-Jan-2024

Rendering a Component

Understanding Rendering in React:

Rendering in React refers to the process of displaying React components on the user interface. React employs a virtual DOM (Document Object Model) to efficiently update and render components. When there's a change in the application state, React compares the virtual DOM with the actual DOM and updates only the necessary components, leading to improved performance.

1. Basic Component Rendering:

Creating a simple React component involves defining a function or class that returns JSX. Here's a basic example:


import React from 'react'; const MyComponent = () => { return ( <div> <h1>Hello, React!</h1> </div> ); }; export default MyComponent;


2. Conditional Rendering:

Conditional rendering allows components to display different content based on certain conditions. Consider the following example where a greeting is displayed only if a isLoggedIn prop is true:


// ConditionalRendering.js import React, { useState } from 'react'; const ConditionalRendering = () => { const [isLoggedIn, setLoggedIn] = useState(false); return ( <div> {isLoggedIn ? ( <p>Welcome, User!</p> ) : ( <button onClick={() => setLoggedIn(true)}>Log In</button> )} </div> ); }; export default ConditionalRendering;



3. List Rendering:

Rendering lists of data is a common scenario in web applications. React makes it easy to map over arrays and render dynamic content. Here's an example rendering a list of items:


// ListRendering.js import React from 'react'; const ListRendering = () => { const fruits = ['Apple', 'Banana', 'Orange']; return ( <ul> {fruits.map((fruit, index) => ( <li key={index}>{fruit}</li> ))} </ul> ); }; export default ListRendering;


4. Optimizing Rendering:

To enhance performance, React provides optimization techniques such as shouldComponentUpdate (for class components) and React.memo (for functional components). Memoization helps prevent unnecessary re-renders. Here's an example using React.memo:


import React from 'react'; const MemoizedComponent = React.memo(({ data }) => { // Component logic }); export default MemoizedComponent;



Comments