DEV Community

Ansh Sheladiya
Ansh Sheladiya

Posted on

React Native vs React.js: Key Differences, Examples, and When to Use Each

React Native vs React.js is a common question for developers deciding how to build modern applications. Both technologies use React's component-based architecture, JavaScript, and declarative UI principles, but they target different platforms and solve different problems.

React.js is primarily used to build interactive web applications that run in browsers, while React Native helps developers build native mobile applications for Android and iOS. Understanding their differences can help you choose the right technology for your project, team, and long-term maintenance strategy.

In this guide, we will compare their rendering approaches, components, styling, performance considerations, development workflows, and practical use cases. We will also explore a runnable JavaScript example that demonstrates how both approaches can share application logic while using platform-specific interfaces.

React Native vs React.js: Architecture, Differences, and Practical Examples

1. What Is React.js?

React.js is a JavaScript library for building user interfaces, primarily for websites and web applications. It allows developers to create reusable components, manage state, respond to user interactions, and efficiently update the browser interface when application data changes.

React components commonly render HTML elements such as div, button, and input. Styling is typically handled through CSS, CSS modules, utility frameworks, or CSS-in-JS libraries, while routing can be implemented with libraries such as React Router.

2. What Is React Native?

React Native is a framework for building native mobile applications using React and JavaScript. Instead of rendering browser HTML elements, it uses components such as View, Text, Pressable, and TextInput to create mobile interfaces through the platform's native rendering infrastructure.

React Native supports Android and iOS, with additional platform capabilities available through its ecosystem. Developers can reuse business logic and many application components across platforms, although certain features require platform-specific implementations or native modules.

3. Key Differences Between React Native and React.js

Rendering: React.js renders interfaces in a browser using the DOM, while React Native renders mobile interfaces using native platform components. This distinction affects component selection, styling, accessibility, and integration with device capabilities.

Styling: React.js commonly uses CSS and browser styling features. React Native uses JavaScript style objects with properties inspired by CSS, but its styling system does not support every browser CSS feature and has its own layout behavior.

Navigation: Web applications generally use URL-based routing and browser navigation. Mobile applications commonly use stack navigation, tab navigation, or other mobile navigation patterns, often implemented with libraries such as React Navigation.

Platform capabilities: React.js can access browser APIs, subject to browser permissions and security restrictions. React Native can integrate with mobile features such as cameras, notifications, location services, and native device APIs through supported APIs and libraries.

Performance: Performance depends on implementation, rendering work, network requests, and the application's architecture. React.js performance is influenced by browser rendering and JavaScript execution, while React Native performance also depends on native rendering, JavaScript work, and communication with platform capabilities.

4. Can You Share Code Between React.js and React Native?

Yes. Both technologies can share business logic, data validation, API clients, authentication helpers, utility functions, and many state-management patterns. However, browser-specific elements and mobile-specific UI components generally need separate implementations.

For example, an order total calculation does not depend on whether the interface runs in a browser or a mobile application. The interface displaying that total does depend on the platform: React.js might use a div, while React Native would use View and Text.

5. Practical JavaScript Example

The following example demonstrates a platform-independent shopping cart calculation. It uses ordinary JavaScript functions to calculate subtotals, discounts, and final prices, then prints the results with step-by-step console messages.

This example runs directly in Node.js or a browser console because it does not depend on React or React Native packages. In a real application, the shared functions could live in a common module imported by separate React.js and React Native interfaces.

6. When Should You Choose Each Technology?

Choose React.js when you need a website, dashboard, admin panel, e-commerce storefront, content platform, or browser-based SaaS application. It is particularly suitable when search engine visibility, URLs, responsive layouts, and integration with browser capabilities are important requirements.

Choose React Native when you need Android and iOS applications with mobile-oriented navigation, device integrations, and platform-specific user experiences. It can reduce duplicated application logic across mobile platforms, but it does not eliminate all native development or platform-specific work.

If your product needs both a website and mobile apps, using React.js and React Native together can be a practical strategy. Sharing domain logic and API contracts while maintaining separate platform-specific interfaces often provides a good balance between reuse and user experience.

/*
 * React Native vs React.js
 * Shared business logic demonstration
 *
 * Run with: node react-comparison.js
 *
 * This file uses plain JavaScript so the same calculation
 * logic can be reused by web and mobile applications.
 */

// Step 1: Define reusable product data.
const products = [
  { id: 1, name: "Wireless Mouse", price: 799, quantity: 2 },
  { id: 2, name: "Mechanical Keyboard", price: 2499, quantity: 1 },
  { id: 3, name: "USB-C Cable", price: 299, quantity: 3 }
];

console.log("Step 1: Product data loaded.");
console.log(`Number of products: ${products.length}`);

// Step 2: Calculate the subtotal without modifying the input.
function calculateSubtotal(items) {
  return items.reduce((total, item) => {
    return total + item.price * item.quantity;
  }, 0);
}

console.log("\nStep 2: Calculating subtotal...");
const subtotal = calculateSubtotal(products);
console.log(`Subtotal: ₹${subtotal.toFixed(2)}`);

// Step 3: Calculate a percentage discount.
function calculateDiscount(amount, percentage) {
  if (amount < 0 || percentage < 0 || percentage > 100) {
    throw new RangeError("Invalid amount or discount percentage.");
  }

  return amount * (percentage / 100);
}

console.log("\nStep 3: Applying a 10% discount...");
const discountPercentage = 10;
const discount = calculateDiscount(subtotal, discountPercentage);
console.log(`Discount: ₹${discount.toFixed(2)}`);

// Step 4: Calculate shipping using a reusable business rule.
function calculateShipping(amount) {
  // Example policy: shipping is free for orders of ₹2,000 or more.
  return amount >= 2000 ? 0 : 99;
}

console.log("\nStep 4: Calculating shipping...");
const discountedSubtotal = subtotal - discount;
const shipping = calculateShipping(discountedSubtotal);
console.log(`Shipping: ₹${shipping.toFixed(2)}`);

// Step 5: Produce a complete order summary.
function createOrderSummary(items, discountRate) {
  const orderSubtotal = calculateSubtotal(items);
  const orderDiscount = calculateDiscount(orderSubtotal, discountRate);
  const amountAfterDiscount = orderSubtotal - orderDiscount;
  const orderShipping = calculateShipping(amountAfterDiscount);

  return {
    itemCount: items.reduce((count, item) => count + item.quantity, 0),
    subtotal: orderSubtotal,
    discount: orderDiscount,
    shipping: orderShipping,
    total: amountAfterDiscount + orderShipping
  };
}

console.log("\nStep 5: Building the final order summary...");
const summary = createOrderSummary(products, discountPercentage);

// Step 6: Format the data for display on any platform.
function formatCurrency(amount) {
  return `₹${amount.toFixed(2)}`;
}

console.log("\nStep 6: Order summary");
console.log("------------------------------");
console.log(`Total items: ${summary.itemCount}`);
console.log(`Subtotal: ${formatCurrency(summary.subtotal)}`);
console.log(`Discount: ${formatCurrency(summary.discount)}`);
console.log(`Shipping: ${formatCurrency(summary.shipping)}`);
console.log(`Final total: ${formatCurrency(summary.total)}`);
console.log("------------------------------");

// Step 7: Demonstrate a simple validation check.
function validateProducts(items) {
  return items.every((item) => {
    return (
      Number.isFinite(item.price) &&
      item.price >= 0 &&
      Number.isInteger(item.quantity) &&
      item.quantity > 0
    );
  });
}

console.log("\nStep 7: Validating cart data...");
console.log(`Cart is valid: ${validateProducts(products)}`);

// Step 8: Export functions when this file is used as a CommonJS module.
// A React.js or React Native project can import shared logic
// from an appropriate module in its own application architecture.
if (typeof module !== "undefined" && module.exports) {
  module.exports = {
    calculateSubtotal,
    calculateDiscount,
    calculateShipping,
    createOrderSummary,
    formatCurrency,
    validateProducts
  };
}

console.log("\nExample completed successfully.");
Enter fullscreen mode Exit fullscreen mode

Conclusion

React Native and React.js share the same React philosophy, but they serve different application platforms. React.js is primarily designed for browser-based experiences, while React Native focuses on building mobile applications with native platform integration.

The most important architectural decision is to separate reusable business logic from platform-specific user interfaces. This makes it easier to maintain consistent calculations, validation rules, and data handling without forcing web and mobile applications to share components that were designed for different environments.

For JavaScript developers, learning React.js first can establish a strong foundation in components, props, state, hooks, and application architecture. Moving to React Native then becomes easier because many concepts remain familiar, even though styling, navigation, platform APIs, and release workflows differ.

Ultimately, choose the technology that best fits your users and product requirements rather than treating one as universally better. Are you planning to build a web application, a mobile app, or both with a shared JavaScript codebase?

Top comments (0)