Module Pattern

The module pattern in javascript allows you to split up your code into smaller, reusable pieces along with keeping certain values within your file private.

How to use this technique in React in an effective manner?

import React, { useState } from 'react';
import inventoryModule from './inventory-module';

const App = () => {
    const [inventory, setInventory] = useState(inventoryModule.getInventoryItems());
  const [itemName, setItemName] = useState('');
  const [itemPrice, setItemPrice] = useState(0);
  const [itemQuantity, setItemQuantity] = useState(1);

  const handleAddToInventory = () => {
    const newItem = {
        id: Math.random().toString(36).substring(7),
        name: itemName,
        price: itemPrice,
        quantity: itemQuantity,
    }
    inventoryModule.addToInventory(newItem);
    setInventory(inventoryModule.getInventoryItems());
    setItemName("");
    setItemPrice(0);
    setItemQuantity(1);
  };

  const handleRemoveFromInventory = (itemId) => {
    inventoryModule.removeFromInventory(itemId);
    setInventory(inventoryModule.getInventoryItems());
  };

  return (
      <div>
        <h1>Inventory</h1>
      <ul>
        {inventory.map((item) => (
            <li key={item.id}>
              {item.name} - ${item.price} - Quantity: {item.quantity}
            <button onClick={() => handleRemoveFromInventory(item.id)}>
              Remove
            </button>
            </li>
        ))}
      </ul>
      <h3>Total Price: ${inventoryModule.getTotalPrice.toFixed()}</h3>
      <input type="text" placeholder="Item Name" value={itemName} 
      onChange={(e) => setItemName(e.target.value)} />
      <input type="number" placeholder="Item Price" value={itemPrice} 
      onChange={(e) => setItemPrice(parseFloat(e.target.value))} />
       <input type="number" placeholder="Item Quantity" value={itemQuantity} 
      onChange={(e) => setItemQuantity(parseInt(e.target.value))} />
       <button onClick={handleAddToInventory}>Add to Inventory</button>
      </div>
  );
};

export default App;

Module file:

const inventoryModule = (() => {

  let inventory = [];
  const TAX_RATE = 0.1;

  const calculateTotalPrice = () => {
      const subTotal = inventory.reduce((acc, item) => {
        return acc + item.price * item.quantity;
    }, 0);
    const tax = subTotal * TAX_RATE;
    return tax + subTotal;
  };


  return {
      addToInventory: (item) => {
        inventory.push();
    },

    removeFromInventory: (itemId) => {
        inventory = inventory.filter((item) => item.id !== itemId);
    },
    getInventoryItems: () => inventory,
    getTotalPrice: () => calculateTotalPrice();


    },
  }
})();

export default inventoryModule;

The above was just a simple demonstration on how to use module pattern.

Hope you got a brief idea on how to implement the same.
Thank you for reading!