React Rendering

Understanding How UI Updates in React

Rendering in React refers to the process of transforming component structures into visible elements on the screen. React employs a virtual representation of the UI, known as the Virtual DOM, to optimize updates and efficiently manage re-rendering.


Understanding Rendering in React

React components are functions or classes that return elements, which describe what should appear in the browser. When a component receives new data (via props or state), React decides whether the UI should update.


Basic Syntax of Rendering

Rendering in React is primarily managed through components. Below is a simple component example:

Example:

function Greeting() {
  return <h1>Hello, World!</h1>;
}

This component returns an <h1> element, which React processes and updates within the browser’s Document Object Model (DOM).


Rendering Mechanisms in React

1. Initial Rendering

When an application first loads, React mounts the components and converts JSX into actual HTML elements.

Example:

import React from "react";
import ReactDOM from "react-dom";

function App() {
  return <h1>Welcome to React</h1>;
}

ReactDOM.createRoot(document.getElementById("root")).render();

2. Re-Rendering with State Changes

React updates components when their state changes, leading to re-rendering.

Example:

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
        <p>Count: {count}</p>
        <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Whenever the button is clicked, setCount updates the state, causing React to re-render the component with the new value.


3. Rendering with Props

Props allow data to pass between components, triggering updates when they change.

Example:

function WelcomeMessage({ username }) {
  return <h2>Hello, {username}!</h2>;
}

function App() {
  return <WelcomeMessage username="Sahand" />;
}

Here, WelcomeMessage re-renders whenever the username prop changes


4. Conditional Rendering

React enables rendering components based on conditions.

Example:

function Notification({ show }) {
  return show ? <p>You have new messages!</p> : null;
}

If show is true, the message appears; otherwise, it doesn’t render.


5. Preventing Unnecessary Re-Renders

To optimize performance, React offers mechanisms like React.memo() and useMemo().

Using React.memo()

Prevents re-rendering unless props change.

Example:

import React from "react";

const MemoizedComponent = React.memo(({ value }) => {
  console.log("Rendering...");
  return <p>{value}</p>;
});

function Parent() {
  return <MemoizedComponent value="Hello" />;
}

6. Rendering Lists

React can dynamically generate UI elements from arrays.

Example:

function TaskList({ tasks }) {
  return (
    <ul>
      {tasks.map((task) => (
        <li key={task.id}>{task.name}</li>
      ))}
    </ul>
  );
}

Here, each task is rendered dynamically using .map().


7. Using useEffect for Rendering Side Effects

Components may need to perform actions after rendering, such as fetching data.

Example:

import { useEffect, useState } from "react";

function DataFetcher() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch("https://api.example.com/data")
      .then((res) => res.json())
      .then((result) => setData(result));
  }, []);

  return  <pre>{JSON.stringify(data, null, 2)} </pre>;
}

The useEffect hook ensures the data fetch occurs after the component mounts.


Conclusion

Understanding rendering in React is crucial for building efficient applications. By leveraging state management, props, conditional rendering, memoization, and effects, developers can optimize performance and ensure a seamless user experience.


Previous Next