ReasonJun

React : Why use React? (Comparing javascript and react code) 본문

Frontend/React

React : Why use React? (Comparing javascript and react code)

ReasonJun 2023. 6. 11. 00:16
728x90

JavaScript Code:

// JavaScript code for rendering a list of names
const names = ['Alice', 'Bob', 'Charlie'];

const listContainer = document.getElementById('list-container');
const list = document.createElement('ul');

names.forEach(name => {
  const listItem = document.createElement('li');
  listItem.innerText = name;
  list.appendChild(listItem);
});

listContainer.appendChild(list);

React Code:

// React code for rendering a list of names
import React from 'react';

const names = ['Alice', 'Bob', 'Charlie'];

const ListComponent = () => {
  return (
    <ul>
      {names.map(name => (
        <li key={name}>{name}</li>
      ))}
    </ul>
  );
};

export default ListComponent;

Advantages of React:

  1. Component-Based Structure: In React, we define a ListComponent as a reusable component, which encapsulates the logic and rendering of the list. This promotes code reusability and modularity.
  2. Declarative Syntax: In the React code, we declare the desired structure of the list using JSX, a declarative syntax. We specify how each list item should be rendered based on the data, rather than manually manipulating the DOM. This makes the code more readable and maintainable.
  3. Efficient Rendering with Virtual DOM: React efficiently updates and renders only the necessary components that have changed. It utilizes the Virtual DOM to compare the previous and current states of the UI and performs minimal DOM manipulations. This improves performance by reducing unnecessary updates and renders.
  4. Component Reusability and Composability: The ListComponent in React can be easily reused across different parts of the application, allowing us to create multiple instances of the list with different data. Components can also be composed together to build complex UI structures, promoting code reuse and maintainability.
  5. Seamless Integration: React can be seamlessly integrated into existing JavaScript projects. It allows for incremental adoption, where you can start introducing React components gradually without rewriting the entire codebase. This makes it easier to leverage React's benefits in an existing JavaScript project.
  6. Rich Ecosystem: React has a vast ecosystem of libraries, tools, and community support. This ecosystem provides additional functionalities, utility libraries, and development tools that enhance the development process. It allows developers to leverage pre-built solutions and learn from the experiences of the community.

By using React, we benefit from its component-based structure, declarative syntax, efficient rendering with the Virtual DOM, and a rich ecosystem. These advantages make development more efficient, maintainable, and scalable compared to traditional JavaScript approaches.

 

728x90
Comments